|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the API Platform project. |
| 5 | + * |
| 6 | + * (c) Kévin Dunglas <dunglas@gmail.com> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +declare(strict_types=1); |
| 13 | + |
| 14 | +namespace ApiPlatform\JsonLd\Serializer; |
| 15 | + |
| 16 | +use ApiPlatform\State\ApiResource\Error; |
| 17 | +use ApiPlatform\Symfony\Validator\Exception\ValidationException as SymfonyValidationException; |
| 18 | +use ApiPlatform\Validator\Exception\ValidationException; |
| 19 | +use Symfony\Component\Serializer\Normalizer\NormalizerInterface; |
| 20 | + |
| 21 | +final class ErrorNormalizer implements NormalizerInterface |
| 22 | +{ |
| 23 | + use HydraPrefixTrait; |
| 24 | + |
| 25 | + public function __construct(private readonly NormalizerInterface $inner, private readonly array $defaultContext = []) |
| 26 | + { |
| 27 | + } |
| 28 | + |
| 29 | + public function normalize(mixed $object, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null |
| 30 | + { |
| 31 | + $normalized = $this->inner->normalize($object, $format, $context); |
| 32 | + $hydraPrefix = $this->getHydraPrefix($context + $this->defaultContext); |
| 33 | + if (!$hydraPrefix) { |
| 34 | + return $normalized; |
| 35 | + } |
| 36 | + |
| 37 | + if (isset($normalized['description'])) { |
| 38 | + $normalized['hydra:description'] = $normalized['description']; |
| 39 | + } |
| 40 | + |
| 41 | + if (isset($normalized['title'])) { |
| 42 | + $normalized['hydra:title'] = $normalized['title']; |
| 43 | + } |
| 44 | + |
| 45 | + return $normalized; |
| 46 | + } |
| 47 | + |
| 48 | + public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool |
| 49 | + { |
| 50 | + return $this->inner->supportsNormalization($data, $format, $context) |
| 51 | + && (is_a($data, Error::class) || is_a($data, ValidationException::class) || is_a($data, SymfonyValidationException::class)); |
| 52 | + } |
| 53 | + |
| 54 | + public function getSupportedTypes(?string $format): array |
| 55 | + { |
| 56 | + return $this->inner->getSupportedTypes($format); |
| 57 | + } |
| 58 | +} |
0 commit comments