JsonBodyConverter::getOptions()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 2
ccs 0
cts 0
cp 0
crap 2
rs 10
1
<?php
2
3
namespace App\ParamConverter;
4
5
use App\Rest\ValidationFailedException;
6
use Exception;
7
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
8
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface;
9
use Symfony\Component\HttpFoundation\Request;
10
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
11
use Symfony\Component\Serializer\SerializerInterface;
12
use Symfony\Component\Validator\Validator\ValidatorInterface;
13
14
class JsonBodyConverter implements ParamConverterInterface {
15
16
    private const ContentType = 'json';
17
18
    private array $defaultOptions = [
19
        'validate' => true,
20
        'version' => null,
21
        'groups' => null
22
    ];
23
24
    public function __construct(private readonly string $prefix, private readonly SerializerInterface $serializer, private readonly ValidatorInterface $validator)
25
    {
26
    }
27
28
    /**
29
     * @inheritDoc
30
     * @throws BadRequestHttpException
31
     */
32
    public function apply(Request $request, ParamConverter $configuration): bool {
33 14
        $contentType = $request->getContentType();
0 ignored issues
show
Deprecated Code introduced by
The function Symfony\Component\HttpFo...quest::getContentType() has been deprecated: since Symfony 6.2, use getContentTypeFormat() instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

33
        $contentType = /** @scrutinizer ignore-deprecated */ $request->getContentType();

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
34 14
35
        if($contentType !== self::ContentType) {
36 14
            throw new BadRequestHttpException(sprintf('Request header "Content-Type" must be "application/json", "%s" provided.', $contentType));
37 14
        }
38 14
39 14
        $name = $configuration->getName();
40
        $class = $configuration->getClass();
41
        $json = $request->getContent();
42
43
        $options = $this->getOptions($configuration);
44
45
        try {
46
            $object = $this->serializer->deserialize($json, $class, 'json');
47
48
            if($options['validate'] === true) {
49
                $validations = $this->validator->validate($object);
50
51
                if($validations->count() > 0) {
52
                    throw new ValidationFailedException($validations);
53
                }
54
            }
55
56
            $request->attributes->set($name, $object);
57
        } catch (Exception) {
58
            throw new BadRequestHttpException('Request body does not contain valid JSON.');
59
        }
60
61
        return true;
62
    }
63
64
    /**
65
     * @inheritDoc
66
     */
67
    public function supports(ParamConverter $configuration): bool {
68
        $class = $configuration->getClass();
69
70
        if(str_starts_with($class, $this->prefix)) {
71
            return true;
72
        }
73
74
        return false;
75
    }
76
77
    private function getOptions(ParamConverter $configuration): array {
78
        return array_replace($this->defaultOptions, $configuration->getOptions());
79
    }
80
81
}