Completed
Push — master ( 12871f...2fd1c3 )
by Amrouche
17s
created

PropertyFilter::apply()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 8
nc 5
nop 4
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\Filter;
15
16
use Symfony\Component\HttpFoundation\Request;
17
18
/**
19
 * Property filter.
20
 *
21
 * @author Baptiste Meyer <[email protected]>
22
 */
23
final class PropertyFilter implements FilterInterface
24
{
25
    private $overrideDefaultProperties;
26
    private $parameterName;
27
    private $whitelist;
28
29
    public function __construct(string $parameterName = 'properties', bool $overrideDefaultProperties = false, array $whitelist = null)
30
    {
31
        $this->overrideDefaultProperties = $overrideDefaultProperties;
32
        $this->parameterName = $parameterName;
33
        $this->whitelist = $whitelist;
34
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39
    public function apply(Request $request, bool $normalization, array $attributes, array &$context)
40
    {
41
        if (!is_array($properties = $request->query->get($this->parameterName))) {
42
            return;
43
        }
44
45
        if (null !== $this->whitelist) {
46
            $properties = array_intersect_key($this->whitelist, $properties);
47
        }
48
49
        if (!$this->overrideDefaultProperties && isset($context['attributes'])) {
50
            $properties = array_merge_recursive((array) $context['attributes'], $properties);
51
        }
52
53
        $context['attributes'] = $properties;
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59
    public function getDescription(string $resourceClass): array
60
    {
61
        return [
62
            $this->parameterName.'[]' => [
63
                'property' => null,
64
                'type' => 'string',
65
                'required' => false,
66
            ],
67
        ];
68
    }
69
}
70