FormErrorNormalizer.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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\Form\FormInterface;
  12. /**
  13. * Normalizes invalid Form instances.
  14. */
  15. final class FormErrorNormalizer implements NormalizerInterface, CacheableSupportsMethodInterface
  16. {
  17. public const TITLE = 'title';
  18. public const TYPE = 'type';
  19. public const CODE = 'status_code';
  20. /**
  21. * {@inheritdoc}
  22. */
  23. public function normalize($object, $format = null, array $context = []): array
  24. {
  25. $data = [
  26. 'title' => $context[self::TITLE] ?? 'Validation Failed',
  27. 'type' => $context[self::TYPE] ?? 'https://symfony.com/errors/form',
  28. 'code' => $context[self::CODE] ?? null,
  29. 'errors' => $this->convertFormErrorsToArray($object),
  30. ];
  31. if (0 !== \count($object->all())) {
  32. $data['children'] = $this->convertFormChildrenToArray($object);
  33. }
  34. return $data;
  35. }
  36. /**
  37. * {@inheritdoc}
  38. */
  39. public function supportsNormalization($data, $format = null): bool
  40. {
  41. return $data instanceof FormInterface && $data->isSubmitted() && !$data->isValid();
  42. }
  43. private function convertFormErrorsToArray(FormInterface $data): array
  44. {
  45. $errors = [];
  46. foreach ($data->getErrors() as $error) {
  47. $errors[] = [
  48. 'message' => $error->getMessage(),
  49. 'cause' => $error->getCause(),
  50. ];
  51. }
  52. return $errors;
  53. }
  54. private function convertFormChildrenToArray(FormInterface $data): array
  55. {
  56. $children = [];
  57. foreach ($data->all() as $child) {
  58. $childData = [
  59. 'errors' => $this->convertFormErrorsToArray($child),
  60. ];
  61. if (!empty($child->all())) {
  62. $childData['children'] = $this->convertFormChildrenToArray($child);
  63. }
  64. $children[$child->getName()] = $childData;
  65. }
  66. return $children;
  67. }
  68. /**
  69. * {@inheritdoc}
  70. */
  71. public function hasCacheableSupportsMethod(): bool
  72. {
  73. return __CLASS__ === static::class;
  74. }
  75. }