| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
namespace Symfony\Component\Serializer\Normalizer; |
| 13 |
|
| 14 |
use Symfony\Component\Form\FormInterface; |
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
final class FormErrorNormalizer implements NormalizerInterface |
| 20 |
{ |
| 21 |
public const TITLE = 'title'; |
| 22 |
public const TYPE = 'type'; |
| 23 |
public const CODE = 'status_code'; |
| 24 |
|
| 25 |
public function normalize(mixed $data, ?string $format = null, array $context = []): array |
| 26 |
{ |
| 27 |
$error = [ |
| 28 |
'title' => $context[self::TITLE] ?? 'Validation Failed', |
| 29 |
'type' => $context[self::TYPE] ?? 'https://symfony.com/errors/form', |
| 30 |
'code' => $context[self::CODE] ?? null, |
| 31 |
'errors' => $this->convertFormErrorsToArray($data), |
| 32 |
]; |
| 33 |
|
| 34 |
if (0 !== \count($data->all())) { |
| 35 |
$error['children'] = $this->convertFormChildrenToArray($data); |
| 36 |
} |
| 37 |
|
| 38 |
return $error; |
| 39 |
} |
| 40 |
|
| 41 |
public function getSupportedTypes(?string $format): array |
| 42 |
{ |
| 43 |
return [ |
| 44 |
FormInterface::class => false, |
| 45 |
]; |
| 46 |
} |
| 47 |
|
| 48 |
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool |
| 49 |
{ |
| 50 |
return $data instanceof FormInterface && $data->isSubmitted() && !$data->isValid(); |
| 51 |
} |
| 52 |
|
| 53 |
private function convertFormErrorsToArray(FormInterface $data): array |
| 54 |
{ |
| 55 |
$errors = []; |
| 56 |
|
| 57 |
foreach ($data->getErrors() as $error) { |
| 58 |
$errors[] = [ |
| 59 |
'message' => $error->getMessage(), |
| 60 |
'cause' => $error->getCause(), |
| 61 |
]; |
| 62 |
} |
| 63 |
|
| 64 |
return $errors; |
| 65 |
} |
| 66 |
|
| 67 |
private function convertFormChildrenToArray(FormInterface $data): array |
| 68 |
{ |
| 69 |
$children = []; |
| 70 |
|
| 71 |
foreach ($data->all() as $child) { |
| 72 |
$childData = [ |
| 73 |
'errors' => $this->convertFormErrorsToArray($child), |
| 74 |
]; |
| 75 |
|
| 76 |
if ($child->all()) { |
| 77 |
$childData['children'] = $this->convertFormChildrenToArray($child); |
| 78 |
} |
| 79 |
|
| 80 |
$children[$child->getName()] = $childData; |
| 81 |
} |
| 82 |
|
| 83 |
return $children; |
| 84 |
} |
| 85 |
} |