Repository navigation
Expand file tree
/
Copy pathCustom.php
More file actions
83 lines (68 loc) · 2.18 KB
/
Copy pathCustom.php
File metadata and controls
83 lines (68 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
declare(strict_types=1);
namespace ItalyStrap\ThemeJsonGenerator\Settings;
use ItalyStrap\ThemeJsonGenerator\Schema\ThemeSchemaCoverage;
use ItalyStrap\ThemeJsonGenerator\Settings;
use ItalyStrap\ThemeJsonGenerator\Settings\Custom\Custom as CustomPreset;
final readonly class Custom
{
use ScopedSettingsWriterTrait;
public const SECTION = 'custom';
public function __construct(
private Settings $settings,
) {
}
/**
* @param list<string>|string $key
*/
#[ThemeSchemaCoverage([Settings::SECTION, self::SECTION])]
public function add(array|string $key, string $value): self
{
$this->settings->addPreset(new CustomPreset($key, $value));
return $this;
}
/**
* @param array<array-key, mixed> $customs
*/
#[ThemeSchemaCoverage([Settings::SECTION, self::SECTION])]
public function addMultiple(array $customs): self
{
$this->presetsToFlat($customs, [], true);
return $this;
}
/**
* @param array<array-key, mixed> $customs
* @param list<string> $prefix
*/
private function presetsToFlat(array $customs, array $prefix, bool $isFirstLevel): void
{
foreach ($customs as $key => $value) {
$fullKey = [...$prefix, (string) $key];
if ($value instanceof CustomPreset) {
if (!$isFirstLevel) {
throw new \InvalidArgumentException(
\sprintf(
'CustomPreset "%s" at key "%s" is supported only at the first level.',
$value->slug(),
$this->formatKey($fullKey)
)
);
}
$this->settings->addPreset($value);
continue;
}
if (\is_array($value)) {
$this->presetsToFlat($value, $fullKey, false);
continue;
}
$this->settings->addPreset(new CustomPreset($fullKey, $value));
}
}
/**
* @param list<string> $segments
*/
private function formatKey(array $segments): string
{
return \implode('.', $segments);
}
}