| 1 | <?php |
||
| 6 | class DeepArray |
||
| 7 | { |
||
| 8 | |||
| 9 | protected bool $trim = false; |
||
|
|
|||
| 10 | |||
| 11 | public function setTrim(bool $trim = false): static |
||
| 12 | { |
||
| 13 | $this->trim = $trim; |
||
| 14 | return $this; |
||
| 15 | 2 | } |
|
| 16 | |||
| 17 | 2 | public function getTrim(): bool |
|
| 18 | 2 | { |
|
| 19 | return $this->trim; |
||
| 20 | } |
||
| 21 | 1 | ||
| 22 | public function getAttr(array $name, array &$context, mixed $defaultValue = null): mixed |
||
| 23 | 1 | { |
|
| 24 | $current = array_shift($name); |
||
| 25 | |||
| 26 | if (!array_key_exists($current, $context)) { |
||
| 27 | return $defaultValue; |
||
| 28 | } |
||
| 29 | |||
| 30 | return count($name) |
||
| 31 | ? $this->getAttr($name, $context[$current], $defaultValue) |
||
| 32 | : $context[$current]; |
||
| 33 | 6 | } |
|
| 34 | |||
| 35 | 6 | public function setAttr(array $name, array &$context, mixed $value): static |
|
| 36 | { |
||
| 37 | 6 | $current = array_shift($name); |
|
| 38 | 1 | ||
| 39 | if (count($name) === 0) { |
||
| 40 | $this->setValueToContext($current, $context, $value); |
||
| 41 | 6 | return $this; |
|
| 42 | 5 | } |
|
| 43 | 6 | ||
| 44 | if (!array_key_exists($current, $context) || !is_array($context[$current])) { |
||
| 45 | $context[$current] = []; |
||
| 46 | } |
||
| 47 | |||
| 48 | $this->setAttr($name, $context[$current], $value); |
||
| 49 | |||
| 50 | return $this; |
||
| 51 | } |
||
| 52 | |||
| 53 | 5 | protected function setValueToContext(string $name, array &$context, mixed $value): void |
|
| 54 | { |
||
| 55 | 5 | $context[$name] = $value; |
|
| 56 | |||
| 57 | 5 | if ($value === null && $this->trim) { |
|
| 58 | 5 | unset($context[$name]); |
|
| 59 | 5 | } |
|
| 60 | } |
||
| 61 | } |
||
| 62 |