Completed
Pull Request — master (#2229)
by
unknown
02:50
created

PaginationParamConverter::supports()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 4
cts 8
cp 0.5
rs 9.7333
c 0
b 0
f 0
cc 4
nc 4
nop 1
crap 6
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\Pagination;
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 PaginationParamConverter implements ParamConverterInterface
26
{
27
    /**
28
     * @var DenormalizerInterface
29
     */
30
    private $denormalizer;
31
32
    /**
33
     * @var ValidatorInterface|null
34
     */
35
    private $validator;
36
37 5
    public function __construct(DenormalizerInterface $denormalizer, ?ValidatorInterface $validator = null)
38
    {
39 5
        $this->denormalizer = $denormalizer;
40 5
        $this->validator    = $validator;
41 5
    }
42
43 3
    public function apply(Request $request, ?ParamConverter $configuration)
44
    {
45 3
        $name = $configuration->getName();
46
47 3
        if (false === $request->query->has($name)) {
48 1
            return false;
49
        }
50
51 2
        $pagination = $this->denormalizer->denormalize(
52 2
            $request->query->all($name),
53 2
            $configuration->getClass()
54
        );
55
56 2
        $request->attributes->set($name, $pagination);
57
58 2
        if (null === $this->validator) {
59 2
            return true;
60
        }
61
62
        $errors = $this->validator->validate($pagination);
63
64
        if ($errors->count()) {
65
            $request->attributes->set('errors', $errors);
66
        }
67
68
        return true;
69
    }
70
71 2
    public function supports(ParamConverter $configuration)
72
    {
73 2
        if ('fos_rest.pagination' !== $configuration->getConverter()) {
74
            return false;
75
        }
76
77 2
        if (\is_a($configuration->getClass(), PaginationInterface::class, true)) {
78 2
            return true;
79
        }
80
81
        if (null === $configuration->getClass()) {
82
            return false;
83
        }
84
85
        return true;
86
    }
87
}
88