|
| 1 | +<?php declare(strict_types = 1); |
| 2 | +namespace Templado\Engine; |
| 3 | + |
| 4 | +class FormData { |
| 5 | + |
| 6 | + /** @var string */ |
| 7 | + private $identifier; |
| 8 | + |
| 9 | + /** @var array */ |
| 10 | + private $values; |
| 11 | + |
| 12 | + /** |
| 13 | + * @throws FormDataException |
| 14 | + */ |
| 15 | + public function __construct(string $identifier, array $values) { |
| 16 | + $this->identifier = $identifier; |
| 17 | + $this->values = $this->initValuesFromArray($values); |
| 18 | + } |
| 19 | + |
| 20 | + public function getIdentifier(): string { |
| 21 | + return $this->identifier; |
| 22 | + } |
| 23 | + |
| 24 | + public function hasKey(string $key): bool { |
| 25 | + return \array_key_exists($key, $this->values); |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * @throws FormDataException |
| 30 | + */ |
| 31 | + public function getValue(string $key): string { |
| 32 | + if (!$this->hasKey($key)) { |
| 33 | + throw new FormDataException(\sprintf('No such key: %s', $key)); |
| 34 | + } |
| 35 | + |
| 36 | + /** @psalm-var string */ |
| 37 | + return $this->values[$key]; |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * @throws FormDataException |
| 42 | + */ |
| 43 | + private function initValuesFromArray(array $values, bool $recursion = false): array { |
| 44 | + $result = []; |
| 45 | + |
| 46 | + /** @psalm-suppress MixedAssignment */ |
| 47 | + foreach ($values as $key => $value) { |
| 48 | + if (\is_string($value)) { |
| 49 | + $result[$key] = $value; |
| 50 | + |
| 51 | + continue; |
| 52 | + } |
| 53 | + |
| 54 | + if ($recursion === false && \is_array($value)) { |
| 55 | + $result[$key] = $this->initValuesFromArray($value, true); |
| 56 | + |
| 57 | + continue; |
| 58 | + } |
| 59 | + |
| 60 | + throw new FormDataException( |
| 61 | + \sprintf('Data type "%s" in key "%s" not supported', \gettype($value), $key) |
| 62 | + ); |
| 63 | + } |
| 64 | + |
| 65 | + return $result; |
| 66 | + } |
| 67 | +} |
0 commit comments