1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the FOSRestBundle package. |
5
|
|
|
* |
6
|
|
|
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace FOS\RestBundle\Serializer\Normalizer; |
13
|
|
|
|
14
|
|
|
use Symfony\Component\Form\FormInterface; |
15
|
|
|
use Symfony\Component\Serializer\Normalizer\NormalizerInterface; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Normalizes invalid Form instances. |
19
|
|
|
* |
20
|
|
|
* @author Guilhem N. <[email protected]> |
21
|
|
|
* |
22
|
|
|
* @internal |
23
|
|
|
*/ |
24
|
|
|
class FormErrorNormalizer implements NormalizerInterface |
25
|
|
|
{ |
26
|
|
|
/** |
27
|
|
|
* {@inheritdoc} |
28
|
|
|
*/ |
29
|
|
|
public function normalize($object, $format = null, array $context = []): array |
30
|
|
|
{ |
31
|
|
|
return [ |
32
|
|
|
'code' => isset($context['status_code']) ? $context['status_code'] : null, |
33
|
|
|
'message' => 'Validation Failed', |
34
|
|
|
'errors' => $this->convertFormToArray($object), |
35
|
|
|
]; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* {@inheritdoc} |
40
|
|
|
*/ |
41
|
|
|
public function supportsNormalization($data, $format = null): bool |
42
|
|
|
{ |
43
|
|
|
return $data instanceof FormInterface && $data->isSubmitted() && !$data->isValid(); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* This code has been taken from JMSSerializer. |
48
|
|
|
*/ |
49
|
|
|
private function convertFormToArray(FormInterface $data): array |
50
|
|
|
{ |
51
|
|
|
$form = $errors = []; |
52
|
|
|
|
53
|
|
|
foreach ($data->getErrors() as $error) { |
54
|
|
|
$errors[] = $error->getMessage(); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
if ($errors) { |
|
|
|
|
58
|
|
|
$form['errors'] = $errors; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
$children = []; |
62
|
|
|
foreach ($data->all() as $child) { |
63
|
|
|
if ($child instanceof FormInterface) { |
64
|
|
|
$children[$child->getName()] = $this->convertFormToArray($child); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
if ($children) { |
|
|
|
|
69
|
|
|
$form['children'] = $children; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
return $form; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)
or! empty(...)
instead.