1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Nelexa\RequestDtoBundle\ArgumentResolver; |
6
|
|
|
|
7
|
|
|
use Symfony\Component\HttpFoundation\Request; |
8
|
|
|
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface; |
9
|
|
|
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata; |
10
|
|
|
use Symfony\Component\Serializer\SerializerInterface; |
11
|
|
|
use Symfony\Component\Validator\Validator\ValidatorInterface; |
12
|
|
|
|
13
|
|
|
abstract class AbstractObjectValueResolver implements ArgumentValueResolverInterface |
14
|
|
|
{ |
15
|
|
|
protected SerializerInterface $serializer; |
16
|
|
|
|
17
|
|
|
protected ValidatorInterface $validator; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* AbstractObjectValueResolver constructor. |
21
|
|
|
*/ |
22
|
19 |
|
public function __construct(SerializerInterface $serializer, ValidatorInterface $validator) |
23
|
|
|
{ |
24
|
19 |
|
$this->serializer = $serializer; |
25
|
19 |
|
$this->validator = $validator; |
26
|
19 |
|
} |
27
|
|
|
|
28
|
|
|
abstract protected function serialize(Request $request, ArgumentMetadata $argument): object; |
29
|
|
|
|
30
|
18 |
|
protected function getSerializeFormat(Request $request): string |
31
|
|
|
{ |
32
|
18 |
|
static $supportFormats = ['json', 'xml', 'yaml', 'csv']; |
33
|
18 |
|
static $defaultFormat = 'json'; |
34
|
|
|
|
35
|
18 |
|
$format = $request->getContentType() ?? $defaultFormat; |
36
|
|
|
|
37
|
18 |
|
if (!\in_array($format, $supportFormats, true)) { |
38
|
5 |
|
$format = $defaultFormat; |
39
|
|
|
} |
40
|
|
|
|
41
|
18 |
|
return $format; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @return iterable |
46
|
|
|
*/ |
47
|
18 |
|
public function resolve(Request $request, ArgumentMetadata $argument) |
48
|
|
|
{ |
49
|
18 |
|
$obj = $this->serialize($request, $argument); |
50
|
17 |
|
$violationList = $this->validator->validate($obj); |
51
|
|
|
|
52
|
17 |
|
$request->attributes->set( |
53
|
17 |
|
ConstraintViolationListValueResolver::REQUEST_ATTR_KEY, |
54
|
|
|
$violationList |
55
|
|
|
); |
56
|
|
|
|
57
|
17 |
|
yield $obj; |
58
|
17 |
|
} |
59
|
|
|
} |
60
|
|
|
|