Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
11 / 11 |
|
100.00% |
4 / 4 |
CRAP | |
100.00% |
1 / 1 |
| FieldsSelectorTransformer | |
100.00% |
10 / 10 |
|
100.00% |
4 / 4 |
10 | |
100.00% |
1 / 1 |
| supports | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| transformRead | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| transformWrite | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| normalizeToJsonArray | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
7 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | /** @license For full copyright and license information, please see the LICENSE.md file. */ |
| 6 | |
| 7 | namespace App\Core\Engine\Application\Transformer; |
| 8 | |
| 9 | defined('AMMONLY_APP') || exit('Direct script access is forbidden.'); |
| 10 | |
| 11 | use App\Core\Engine\Domain\Model\FieldMetadata; |
| 12 | |
| 13 | /** |
| 14 | * Fields Selector UiType Transformer. |
| 15 | * |
| 16 | * Handles UiType: fields_selector. |
| 17 | * Read: decodes and normalizes JSON array of field keys. |
| 18 | * Write: validates and serializes field keys into compact JSON array. |
| 19 | * |
| 20 | * @package App\Core\Engine\Application\Transformer |
| 21 | */ |
| 22 | final class FieldsSelectorTransformer implements UiTypeTransformerInterface |
| 23 | { |
| 24 | /** {@inheritdoc} */ |
| 25 | public function supports(string $uitypeName): bool |
| 26 | { |
| 27 | return $uitypeName === 'fields_selector'; |
| 28 | } |
| 29 | |
| 30 | /** {@inheritdoc} */ |
| 31 | public function transformRead(mixed $rawValue, FieldMetadata $field): string |
| 32 | { |
| 33 | return $this->normalizeToJsonArray($rawValue); |
| 34 | } |
| 35 | |
| 36 | /** {@inheritdoc} */ |
| 37 | public function transformWrite(mixed $inputValue, FieldMetadata $field): mixed |
| 38 | { |
| 39 | return $this->normalizeToJsonArray($inputValue); |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * Serializes an array or valid JSON string into a compact JSON array. |
| 44 | * |
| 45 | * @param mixed $value Raw input or database value. |
| 46 | * @return string JSON-encoded array string. |
| 47 | */ |
| 48 | private function normalizeToJsonArray(mixed $value): string |
| 49 | { |
| 50 | if ($value === null || $value === '' || $value === '[]') { |
| 51 | return '[]'; |
| 52 | } |
| 53 | |
| 54 | $items = is_array($value) ? $value : json_decode((string) $value, true); |
| 55 | if (!is_array($items)) { |
| 56 | return '[]'; |
| 57 | } |
| 58 | |
| 59 | $encoded = json_encode(array_values($items), JSON_UNESCAPED_UNICODE); |
| 60 | |
| 61 | return $encoded !== false ? $encoded : '[]'; |
| 62 | } |
| 63 | } |