Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
83.33% |
15 / 18 |
|
50.00% |
2 / 4 |
CRAP | |
0.00% |
0 / 1 |
| DomNormalizer | |
83.33% |
15 / 18 |
|
50.00% |
2 / 4 |
10.46 | |
0.00% |
0 / 1 |
| supportsNormalization | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
2 | |||
| normalize | |
75.00% |
6 / 8 |
|
0.00% |
0 / 1 |
3.14 | |||
| supportsDenormalization | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
2 | |||
| denormalize | |
87.50% |
7 / 8 |
|
0.00% |
0 / 1 |
3.02 | |||
| 1 | <?php |
| 2 | namespace Apie\Serializer\Normalizers; |
| 3 | |
| 4 | use Apie\Core\Lists\ItemHashmap; |
| 5 | use Apie\Core\Lists\ItemList; |
| 6 | use Apie\Core\ValueObjects\Utils; |
| 7 | use Apie\Serializer\Context\ApieSerializerContext; |
| 8 | use Apie\Serializer\Interfaces\DenormalizerInterface; |
| 9 | use Apie\Serializer\Interfaces\NormalizerInterface; |
| 10 | use DOMAttr; |
| 11 | use DOMDocument; |
| 12 | use DOMElement; |
| 13 | use Psr\Http\Message\UploadedFileInterface; |
| 14 | |
| 15 | class DomNormalizer implements NormalizerInterface, DenormalizerInterface |
| 16 | { |
| 17 | public function supportsNormalization(mixed $object, ApieSerializerContext $apieSerializerContext): bool |
| 18 | { |
| 19 | return $object instanceof DOMAttr || $object instanceof DOMElement; |
| 20 | } |
| 21 | |
| 22 | public function normalize(mixed $object, ApieSerializerContext $apieSerializerContext): string |
| 23 | { |
| 24 | if ($object instanceof DOMAttr) { |
| 25 | return $object->name . '="' . htmlspecialchars($object->value, ENT_XML1 | ENT_QUOTES, 'UTF-8') . '"'; |
| 26 | } |
| 27 | |
| 28 | $document = $object->ownerDocument ?? new DOMDocument(); |
| 29 | $node = $object; |
| 30 | if ($object->ownerDocument === null) { |
| 31 | $node = $document->importNode($object, true); |
| 32 | $document->appendChild($node); |
| 33 | } |
| 34 | return (string) $document->saveXML($node); |
| 35 | } |
| 36 | |
| 37 | public function supportsDenormalization(string|int|float|bool|null|ItemList|ItemHashmap|UploadedFileInterface $object, string $desiredType, ApieSerializerContext $apieSerializerContext): bool |
| 38 | { |
| 39 | return $desiredType === DOMAttr::class || $desiredType === DOMElement::class; |
| 40 | } |
| 41 | |
| 42 | public function denormalize(string|int|float|bool|null|ItemList|ItemHashmap|UploadedFileInterface $object, string $desiredType, ApieSerializerContext $apieSerializerContext): DOMAttr|DOMElement |
| 43 | { |
| 44 | $value = Utils::toString($object); |
| 45 | if ($desiredType === DOMAttr::class) { |
| 46 | if (preg_match('/^([A-Za-z_][A-Za-z0-9_.:-]*)="(.*)"$/s', $value, $matches)) { |
| 47 | return new DOMAttr($matches[1], htmlspecialchars_decode($matches[2], ENT_XML1)); |
| 48 | } |
| 49 | return new DOMAttr('value', $value); |
| 50 | } |
| 51 | |
| 52 | $document = new DOMDocument(); |
| 53 | $document->loadXML($value, LIBXML_NONET); |
| 54 | return $document->documentElement; |
| 55 | } |
| 56 | } |