RequestDtoTransform   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 30
dl 0
loc 48
ccs 20
cts 20
cp 1
rs 10
c 1
b 0
f 1
wmc 8

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
B transform() 0 36 7
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Nelexa\RequestDtoBundle\Transform;
6
7
use Nelexa\RequestDtoBundle\Dto\ConstructRequestObjectInterface;
8
use Nelexa\RequestDtoBundle\Dto\QueryObjectInterface;
9
use Nelexa\RequestDtoBundle\Dto\RequestBodyObjectInterface;
10
use Nelexa\RequestDtoBundle\Dto\RequestObjectInterface;
11
use Symfony\Component\HttpFoundation\Request;
12
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
13
use Symfony\Component\Serializer\SerializerInterface;
14
15
class RequestDtoTransform
16
{
17
    private SerializerInterface $serializer;
18
19 26
    public function __construct(SerializerInterface $serializer)
20
    {
21 26
        $this->serializer = $serializer;
22 26
    }
23
24
    /**
25
     * @return QueryObjectInterface|RequestObjectInterface|RequestBodyObjectInterface|ConstructRequestObjectInterface
26
     */
27 25
    public function transform(Request $request, string $className, string $format, array $context = []): object
28
    {
29
        $context += [
30 25
            AbstractObjectNormalizer::DISABLE_TYPE_ENFORCEMENT => true,
31
        ];
32
33 25
        if (is_a($className, QueryObjectInterface::class, true)) {
34 7
            $dto = $this->serializer->denormalize(
35 7
                $request->query->all(),
36
                $className,
37
                $format,
38
                $context
39
            );
40 19
        } elseif (is_a($className, RequestObjectInterface::class, true)) {
41 8
            $dto = $this->serializer->denormalize(
42 8
                $request->isMethod('GET') || $request->isMethod('HEAD') ?
43 2
                    $request->query->all() :
44 8
                    $request->request->all(),
45
                $className,
46
                $format,
47
                $context
48
            );
49 12
        } elseif (is_a($className, RequestBodyObjectInterface::class, true)) {
50 7
            $dto = $this->serializer->deserialize(
51 7
                $request->getContent(),
52
                $className,
53
                $format,
54
                $context
55
            );
56 5
        } elseif (is_a($className, ConstructRequestObjectInterface::class, true)) {
57 4
            $dto = new $className($request);
58
        } else {
59 1
            throw new \RuntimeException('Class ' . $className . ' is not supported.');
60
        }
61
62 22
        return $dto;
63
    }
64
}
65