Completed
Push — master ( 9dfe4a...9f73a9 )
by Alexey
03:27
created

AbstractObjectValueResolver   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 17
c 1
b 0
f 1
dl 0
loc 45
ccs 17
cts 17
cp 1
rs 10
wmc 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getSerializeFormat() 0 12 2
A resolve() 0 11 1
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