vendor/api-platform/core/src/Problem/Serializer/ErrorNormalizer.php line 46

  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\Problem\Serializer;
  12. use Symfony\Component\ErrorHandler\Exception\FlattenException;
  13. use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
  14. use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
  15. /**
  16.  * Normalizes errors according to the API Problem spec (RFC 7807).
  17.  *
  18.  * @see https://tools.ietf.org/html/rfc7807
  19.  *
  20.  * @author Kévin Dunglas <dunglas@gmail.com>
  21.  */
  22. final class ErrorNormalizer implements NormalizerInterfaceCacheableSupportsMethodInterface
  23. {
  24.     use ErrorNormalizerTrait;
  25.     public const FORMAT 'jsonproblem';
  26.     public const TYPE 'type';
  27.     public const TITLE 'title';
  28.     private array $defaultContext = [
  29.         self::TYPE => 'https://tools.ietf.org/html/rfc2616#section-10',
  30.         self::TITLE => 'An error occurred',
  31.     ];
  32.     public function __construct(private readonly bool $debug false, array $defaultContext = [])
  33.     {
  34.         $this->defaultContext array_merge($this->defaultContext$defaultContext);
  35.     }
  36.     /**
  37.      * {@inheritdoc}
  38.      */
  39.     public function normalize(mixed $objectstring $format null, array $context = []): array
  40.     {
  41.         $data = [
  42.             'type' => $context[self::TYPE] ?? $this->defaultContext[self::TYPE],
  43.             'title' => $context[self::TITLE] ?? $this->defaultContext[self::TITLE],
  44.             'detail' => $this->getErrorMessage($object$context$this->debug),
  45.         ];
  46.         if ($this->debug && null !== $trace $object->getTrace()) {
  47.             $data['trace'] = $trace;
  48.         }
  49.         return $data;
  50.     }
  51.     /**
  52.      * {@inheritdoc}
  53.      */
  54.     public function supportsNormalization(mixed $datastring $format null, array $context = []): bool
  55.     {
  56.         return self::FORMAT === $format && ($data instanceof \Exception || $data instanceof FlattenException);
  57.     }
  58.     public function hasCacheableSupportsMethod(): bool
  59.     {
  60.         return true;
  61.     }
  62. }