Spaces:
Runtime error
Runtime error
File size: 2,648 Bytes
7a66774 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Serializer\Normalizer;
use Symfony\Component\Form\FormInterface;
/**
* Normalizes invalid Form instances.
*/
final class FormErrorNormalizer implements NormalizerInterface, CacheableSupportsMethodInterface
{
public const TITLE = 'title';
public const TYPE = 'type';
public const CODE = 'status_code';
public function normalize(mixed $object, ?string $format = null, array $context = []): array
{
$data = [
'title' => $context[self::TITLE] ?? 'Validation Failed',
'type' => $context[self::TYPE] ?? 'https://symfony.com/errors/form',
'code' => $context[self::CODE] ?? null,
'errors' => $this->convertFormErrorsToArray($object),
];
if (0 !== \count($object->all())) {
$data['children'] = $this->convertFormChildrenToArray($object);
}
return $data;
}
public function getSupportedTypes(?string $format): array
{
return [
FormInterface::class => false,
];
}
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof FormInterface && $data->isSubmitted() && !$data->isValid();
}
private function convertFormErrorsToArray(FormInterface $data): array
{
$errors = [];
foreach ($data->getErrors() as $error) {
$errors[] = [
'message' => $error->getMessage(),
'cause' => $error->getCause(),
];
}
return $errors;
}
private function convertFormChildrenToArray(FormInterface $data): array
{
$children = [];
foreach ($data->all() as $child) {
$childData = [
'errors' => $this->convertFormErrorsToArray($child),
];
if ($child->all()) {
$childData['children'] = $this->convertFormChildrenToArray($child);
}
$children[$child->getName()] = $childData;
}
return $children;
}
/**
* @deprecated since Symfony 6.3, use "getSupportedTypes()" instead
*/
public function hasCacheableSupportsMethod(): bool
{
trigger_deprecation('symfony/serializer', '6.3', 'The "%s()" method is deprecated, use "getSupportedTypes()" instead.', __METHOD__);
return true;
}
}
|