ProblemNormalizer.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.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. namespace Symfony\Component\Serializer\Normalizer;
  11. use Symfony\Component\ErrorHandler\Exception\FlattenException;
  12. use Symfony\Component\Serializer\Exception\InvalidArgumentException;
  13. /**
  14. * Normalizes errors according to the API Problem spec (RFC 7807).
  15. *
  16. * @see https://tools.ietf.org/html/rfc7807
  17. *
  18. * @author Kévin Dunglas <dunglas@gmail.com>
  19. * @author Yonel Ceruto <yonelceruto@gmail.com>
  20. */
  21. class ProblemNormalizer implements NormalizerInterface, CacheableSupportsMethodInterface
  22. {
  23. private $debug;
  24. private $defaultContext = [
  25. 'type' => 'https://tools.ietf.org/html/rfc2616#section-10',
  26. 'title' => 'An error occurred',
  27. ];
  28. public function __construct(bool $debug = false, array $defaultContext = [])
  29. {
  30. $this->debug = $debug;
  31. $this->defaultContext = $defaultContext + $this->defaultContext;
  32. }
  33. /**
  34. * {@inheritdoc}
  35. *
  36. * @return array
  37. */
  38. public function normalize($object, string $format = null, array $context = [])
  39. {
  40. if (!$object instanceof FlattenException) {
  41. throw new InvalidArgumentException(sprintf('The object must implement "%s".', FlattenException::class));
  42. }
  43. $context += $this->defaultContext;
  44. $debug = $this->debug && ($context['debug'] ?? true);
  45. $data = [
  46. 'type' => $context['type'],
  47. 'title' => $context['title'],
  48. 'status' => $context['status'] ?? $object->getStatusCode(),
  49. 'detail' => $debug ? $object->getMessage() : $object->getStatusText(),
  50. ];
  51. if ($debug) {
  52. $data['class'] = $object->getClass();
  53. $data['trace'] = $object->getTrace();
  54. }
  55. return $data;
  56. }
  57. /**
  58. * {@inheritdoc}
  59. */
  60. public function supportsNormalization($data, string $format = null): bool
  61. {
  62. return $data instanceof FlattenException;
  63. }
  64. /**
  65. * {@inheritdoc}
  66. */
  67. public function hasCacheableSupportsMethod(): bool
  68. {
  69. return true;
  70. }
  71. }