-
Notifications
You must be signed in to change notification settings - Fork 700
/
Copy pathFormErrorNormalizer.php
81 lines (69 loc) · 1.96 KB
/
FormErrorNormalizer.php
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
<?php
/*
* This file is part of the FOSRestBundle package.
*
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FOS\RestBundle\Serializer\Normalizer;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* Normalizes invalid Form instances.
*
* @author Guilhem N. <[email protected]>
*
* @internal
*/
class FormErrorNormalizer implements NormalizerInterface
{
/**
* {@inheritdoc}
*/
public function normalize($object, $format = null, array $context = []): array
{
return [
'code' => isset($context['status_code']) ? $context['status_code'] : null,
'message' => 'Validation Failed',
'errors' => $this->convertFormToArray($object),
];
}
/**
* {@inheritdoc}
*/
public function supportsNormalization($data, $format = null, array $context = []): bool
{
return $data instanceof FormInterface && $data->isSubmitted() && !$data->isValid();
}
/**
* This code has been taken from JMSSerializer.
*/
private function convertFormToArray(FormInterface $data): array
{
$form = $errors = [];
foreach ($data->getErrors() as $error) {
$errors[] = $error->getMessage();
}
if ($errors) {
$form['errors'] = $errors;
}
$children = [];
foreach ($data->all() as $child) {
if ($child instanceof FormInterface) {
$children[$child->getName()] = $this->convertFormToArray($child);
}
}
if ($children) {
$form['children'] = $children;
}
return $form;
}
public function getSupportedTypes(?string $format): array
{
return [
FormInterface::class => false,
];
}
}