|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace KaririCode\Transformer\Processor\Array; |
| 6 | + |
| 7 | +use KaririCode\Contract\Processor\ConfigurableProcessor; |
| 8 | +use KaririCode\Transformer\Processor\AbstractTransformerProcessor; |
| 9 | +use KaririCode\Transformer\Trait\ArrayTransformerTrait; |
| 10 | + |
| 11 | +class ArrayKeyTransformer extends AbstractTransformerProcessor implements ConfigurableProcessor |
| 12 | +{ |
| 13 | + use ArrayTransformerTrait; |
| 14 | + |
| 15 | + private const CASE_SNAKE = 'snake'; |
| 16 | + private const CASE_CAMEL = 'camel'; |
| 17 | + private const CASE_PASCAL = 'pascal'; |
| 18 | + private const CASE_KEBAB = 'kebab'; |
| 19 | + |
| 20 | + private string $case = self::CASE_SNAKE; |
| 21 | + private bool $recursive = true; |
| 22 | + |
| 23 | + public function configure(array $options): void |
| 24 | + { |
| 25 | + if (isset($options['case']) && in_array($options['case'], $this->getAllowedCases(), true)) { |
| 26 | + $this->case = $options['case']; |
| 27 | + } |
| 28 | + |
| 29 | + $this->recursive = $options['recursive'] ?? $this->recursive; |
| 30 | + } |
| 31 | + |
| 32 | + public function process(mixed $input): array |
| 33 | + { |
| 34 | + if (!is_array($input)) { |
| 35 | + $this->setInvalid('notArray'); |
| 36 | + |
| 37 | + return []; |
| 38 | + } |
| 39 | + |
| 40 | + return $this->transformArrayKeys($input); |
| 41 | + } |
| 42 | + |
| 43 | + private function transformArrayKeys(array $array): array |
| 44 | + { |
| 45 | + $result = []; |
| 46 | + |
| 47 | + foreach ($array as $key => $value) { |
| 48 | + $transformedKey = $this->transformKey((string) $key); |
| 49 | + |
| 50 | + if (is_array($value) && $this->recursive) { |
| 51 | + $result[$transformedKey] = $this->transformArrayKeys($value); |
| 52 | + } else { |
| 53 | + $result[$transformedKey] = $value; |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + return $result; |
| 58 | + } |
| 59 | + |
| 60 | + private function transformKey(string $key): string |
| 61 | + { |
| 62 | + return match ($this->case) { |
| 63 | + self::CASE_SNAKE => $this->toSnakeCase($key), |
| 64 | + self::CASE_CAMEL => $this->toCamelCase($key), |
| 65 | + self::CASE_PASCAL => $this->toPascalCase($key), |
| 66 | + self::CASE_KEBAB => $this->toKebabCase($key), |
| 67 | + default => $key, |
| 68 | + }; |
| 69 | + } |
| 70 | + |
| 71 | + private function getAllowedCases(): array |
| 72 | + { |
| 73 | + return [ |
| 74 | + self::CASE_SNAKE, |
| 75 | + self::CASE_CAMEL, |
| 76 | + self::CASE_PASCAL, |
| 77 | + self::CASE_KEBAB, |
| 78 | + ]; |
| 79 | + } |
| 80 | +} |
0 commit comments