vendor/api-platform/core/src/Hydra/Serializer/ErrorNormalizer.php line 44

  1. <?php
  2. /*
  3.  * This file is part of the API Platform project.
  4.  *
  5.  * (c) Kévin Dunglas <dunglas@gmail.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. declare(strict_types=1);
  11. namespace ApiPlatform\Hydra\Serializer;
  12. use ApiPlatform\Api\UrlGeneratorInterface;
  13. use ApiPlatform\Problem\Serializer\ErrorNormalizerTrait;
  14. use Symfony\Component\ErrorHandler\Exception\FlattenException;
  15. use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
  16. use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
  17. /**
  18.  * Converts {@see \Exception} or {@see FlattenException} to a Hydra error representation.
  19.  *
  20.  * @author Kévin Dunglas <dunglas@gmail.com>
  21.  * @author Samuel ROZE <samuel.roze@gmail.com>
  22.  */
  23. final class ErrorNormalizer implements NormalizerInterfaceCacheableSupportsMethodInterface
  24. {
  25.     use ErrorNormalizerTrait;
  26.     public const FORMAT 'jsonld';
  27.     public const TITLE 'title';
  28.     private array $defaultContext = [self::TITLE => 'An error occurred'];
  29.     public function __construct(private readonly UrlGeneratorInterface $urlGenerator, private readonly bool $debug false, array $defaultContext = [])
  30.     {
  31.         $this->defaultContext array_merge($this->defaultContext$defaultContext);
  32.     }
  33.     /**
  34.      * {@inheritdoc}
  35.      */
  36.     public function normalize(mixed $objectstring $format null, array $context = []): array|string|int|float|bool|\ArrayObject|null
  37.     {
  38.         $data = [
  39.             '@context' => $this->urlGenerator->generate('api_jsonld_context', ['shortName' => 'Error']),
  40.             '@type' => 'hydra:Error',
  41.             'hydra:title' => $context[self::TITLE] ?? $this->defaultContext[self::TITLE],
  42.             'hydra:description' => $this->getErrorMessage($object$context$this->debug),
  43.         ];
  44.         if ($this->debug && null !== $trace $object->getTrace()) {
  45.             $data['trace'] = $trace;
  46.         }
  47.         return $data;
  48.     }
  49.     /**
  50.      * {@inheritdoc}
  51.      */
  52.     public function supportsNormalization(mixed $datastring $format null, array $context = []): bool
  53.     {
  54.         return self::FORMAT === $format && ($data instanceof \Exception || $data instanceof FlattenException);
  55.     }
  56.     public function hasCacheableSupportsMethod(): bool
  57.     {
  58.         return true;
  59.     }
  60. }