Completed
Push — master ( 26f03f...8b815a )
by Kévin
16s queued 10s
created

createFromRequest()   C

Complexity

Conditions 7
Paths 5

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 6.9811
c 0
b 0
f 0
cc 7
eloc 11
nc 5
nop 3
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\Serializer;
15
16
use ApiPlatform\Core\Exception\RuntimeException;
17
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
18
use ApiPlatform\Core\Serializer\Filter\FilterInterface;
19
use ApiPlatform\Core\Util\RequestAttributesExtractor;
20
use Psr\Container\ContainerInterface;
21
use Symfony\Component\HttpFoundation\Request;
22
23
/**
24
 * {@inheritdoc}
25
 *
26
 * @author Baptiste Meyer <[email protected]>
27
 */
28
final class SerializerFilterContextBuilder implements SerializerContextBuilderInterface
29
{
30
    private $decorated;
31
    private $filterLocator;
32
    private $resourceMetadataFactory;
33
34
    public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory, ContainerInterface $filterLocator, SerializerContextBuilderInterface $decorated)
35
    {
36
        $this->decorated = $decorated;
37
        $this->filterLocator = $filterLocator;
38
        $this->resourceMetadataFactory = $resourceMetadataFactory;
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function createFromRequest(Request $request, bool $normalization, array $attributes = null): array
45
    {
46
        if (null === $attributes && !$attributes = RequestAttributesExtractor::extractAttributes($request)) {
47
            throw new RuntimeException('Request attributes are not valid.');
48
        }
49
50
        $context = $this->decorated->createFromRequest($request, $normalization, $attributes);
51
        $resourceMetadata = $this->resourceMetadataFactory->create($attributes['resource_class']);
52
53
        $resourceFilters = $resourceMetadata->getOperationAttribute($attributes, 'filters', [], true);
54
55
        if (!$resourceFilters) {
56
            return $context;
57
        }
58
59
        foreach ($resourceFilters as $filterId) {
60
            if ($this->filterLocator->has($filterId) && ($filter = $this->filterLocator->get($filterId)) instanceof FilterInterface) {
61
                $filter->apply($request, $normalization, $attributes, $context);
62
            }
63
        }
64
65
        return $context;
66
    }
67
}
68