1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace App\Serializer\Normalizer; |
6
|
|
|
|
7
|
|
|
use Symfony\Component\Form\FormInterface; |
8
|
|
|
use Symfony\Component\Serializer\Normalizer\NormalizerInterface; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* FormErrorNormalizer. |
12
|
|
|
* |
13
|
|
|
* @see \FOS\RestBundle\Serializer\Normalizer\FormErrorNormalizer |
14
|
|
|
*/ |
15
|
|
|
final class FormErrorNormalizer implements NormalizerInterface |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* {@inheritdoc} |
19
|
|
|
*/ |
20
|
6 |
|
public function normalize($object, string $format = null, array $context = []): array |
21
|
|
|
{ |
22
|
|
|
$data = [ |
23
|
6 |
|
'code' => $context['status_code'] ?? null, |
24
|
6 |
|
'message' => 'Validation Failed', |
25
|
6 |
|
'errors' => $this->convertFormToArray($object), |
26
|
|
|
]; |
27
|
|
|
|
28
|
6 |
|
if (!\is_array($data)) { |
|
|
|
|
29
|
|
|
throw new \RuntimeException('Normalized form data should be of type array.'); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** @var array $data */ |
33
|
6 |
|
$data = $data['errors']['children']; |
34
|
6 |
|
$data = \array_filter($data, fn (array $child) => isset($child['errors']) && \count($child['errors']) > 0); |
35
|
|
|
|
36
|
6 |
|
return \array_map(fn (array $child) => $child['errors'] ?? [], $data); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* {@inheritdoc} |
41
|
|
|
*/ |
42
|
34 |
|
public function supportsNormalization($data, string $format = null): bool |
43
|
|
|
{ |
44
|
34 |
|
return $data instanceof FormInterface && $data->isSubmitted() && !$data->isValid(); |
45
|
|
|
} |
46
|
|
|
|
47
|
6 |
|
private function convertFormToArray(FormInterface $data): array |
48
|
|
|
{ |
49
|
6 |
|
$form = $errors = []; |
50
|
|
|
|
51
|
6 |
|
foreach ($data->getErrors() as $error) { |
52
|
6 |
|
$errors[] = $error->getMessage(); |
|
|
|
|
53
|
|
|
} |
54
|
|
|
|
55
|
6 |
|
if ($errors) { |
56
|
6 |
|
$form['errors'] = $errors; |
57
|
|
|
} |
58
|
|
|
|
59
|
6 |
|
$children = []; |
60
|
6 |
|
foreach ($data->all() as $child) { |
61
|
6 |
|
if ($child instanceof FormInterface) { |
62
|
6 |
|
$children[$child->getName()] = $this->convertFormToArray($child); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
6 |
|
if ($children) { |
67
|
6 |
|
$form['children'] = $children; |
68
|
|
|
} |
69
|
|
|
|
70
|
6 |
|
return $form; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|