|
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
|
2 |
|
public function normalize($object, $format = null, array $context = []): array |
|
30
|
|
|
{ |
|
31
|
|
|
return [ |
|
32
|
2 |
|
'code' => isset($context['status_code']) ? $context['status_code'] : null, |
|
33
|
2 |
|
'message' => 'Validation Failed', |
|
34
|
2 |
|
'errors' => $this->convertFormToArray($object), |
|
35
|
|
|
]; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* {@inheritdoc} |
|
40
|
|
|
*/ |
|
41
|
18 |
|
public function supportsNormalization($data, $format = null): bool |
|
42
|
|
|
{ |
|
43
|
18 |
|
return $data instanceof FormInterface && $data->isSubmitted() && !$data->isValid(); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
/** |
|
47
|
|
|
* This code has been taken from JMSSerializer. |
|
48
|
|
|
*/ |
|
49
|
2 |
|
private function convertFormToArray(FormInterface $data): array |
|
50
|
|
|
{ |
|
51
|
2 |
|
$form = $errors = []; |
|
52
|
|
|
|
|
53
|
2 |
|
foreach ($data->getErrors() as $error) { |
|
54
|
2 |
|
$errors[] = $error->getMessage(); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
2 |
|
if ($errors) { |
|
|
|
|
|
|
58
|
2 |
|
$form['errors'] = $errors; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
2 |
|
$children = []; |
|
62
|
2 |
|
foreach ($data->all() as $child) { |
|
63
|
2 |
|
if ($child instanceof FormInterface) { |
|
64
|
2 |
|
$children[$child->getName()] = $this->convertFormToArray($child); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
2 |
|
if ($children) { |
|
|
|
|
|
|
69
|
2 |
|
$form['children'] = $children; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
2 |
|
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.