Completed
Pull Request — master (#2230)
by
unknown
02:56
created

QueryStringParamConverter::apply()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4.3731

Importance

Changes 0
Metric Value
dl 0
loc 27
ccs 10
cts 14
cp 0.7143
rs 9.488
c 0
b 0
f 0
cc 4
nc 4
nop 2
crap 4.3731
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the FOSRestBundle package.
7
 *
8
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace FOS\RestBundle\Request;
15
16
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
17
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface;
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
20
use Symfony\Component\Validator\Validator\ValidatorInterface;
21
22
/**
23
 * @author Bartek Chmura <[email protected]>
24
 */
25
final class QueryStringParamConverter implements ParamConverterInterface
26
{
27
    /**
28
     * @var DenormalizerInterface
29
     */
30
    private $denormalizer;
31
32
    /**
33
     * @var ValidatorInterface|null
34
     */
35
    private $validator;
36
37 8
    public function __construct(DenormalizerInterface $denormalizer, ?ValidatorInterface $validator = null)
38
    {
39 8
        $this->denormalizer = $denormalizer;
40 8
        $this->validator = $validator;
41 8
    }
42
43 5
    public function apply(Request $request, ?ParamConverter $configuration)
44
    {
45 5
        $name = $configuration->getName();
46
47 5
        if (false === $request->query->has($name)) {
48 1
            return false;
49
        }
50
51 4
        $object = $this->denormalizer->denormalize(
52 4
            $request->query->all($name),
53 4
            $configuration->getClass()
54
        );
55
56 4
        $request->attributes->set($name, $object);
57
58 4
        if (null === $this->validator) {
59 4
            return true;
60
        }
61
62
        $errors = $this->validator->validate($object);
63
64
        if ($errors->count()) {
65
            $request->attributes->set('errors', $errors);
66
        }
67
68
        return true;
69
    }
70
71 3
    public function supports(ParamConverter $configuration)
72
    {
73 3
        if ('fos_rest.query_string' !== $configuration->getConverter()) {
74
            return false;
75
        }
76
77 3
        if (null === $configuration->getClass()) {
78
            return false;
79
        }
80
81 3
        return true;
82
    }
83
}
84