Passed
Push — feature/publishable ( c26268...7bd202 )
by Daniel
18:12 queued 11:31
created

PublishableContextBuilder::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 2
c 0
b 0
f 0
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
cc 1
nc 1
nop 2
crap 2
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Component Bundle Project
5
 *
6
 * (c) Daniel West <[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 Silverback\ApiComponentBundle\Serializer\ContextBuilder;
15
16
use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;
17
use Silverback\ApiComponentBundle\Helper\PublishableHelper;
18
use Silverback\ApiComponentBundle\Serializer\MappingLoader\PublishableLoader;
19
use Symfony\Component\HttpFoundation\Request;
20
21
/**
22
 * @author Vincent Chalamon <[email protected]>
23
 */
24
final class PublishableContextBuilder implements SerializerContextBuilderInterface
25
{
26
    private SerializerContextBuilderInterface $decorated;
27
    private PublishableHelper $publishableHelper;
28
29
    public function __construct(SerializerContextBuilderInterface $decorated, PublishableHelper $publishableHelper)
30
    {
31
        $this->decorated = $decorated;
32
        $this->publishableHelper = $publishableHelper;
33
    }
34
35
    public function createFromRequest(Request $request, bool $normalization, array $extractedAttributes = null): array
36
    {
37
        $context = $this->decorated->createFromRequest($request, $normalization, $extractedAttributes);
38
        if (empty($resourceClass = $context['resource_class']) || empty($context['groups'])) {
39
            return $context;
40
        }
41
42
        $reflectionClass = new \ReflectionClass($resourceClass);
43
        if ($normalization) {
44
            $context['groups'][] = sprintf('%s:%s:read', $reflectionClass->getShortName(), PublishableLoader::GROUP_NAME);
45
        } elseif ($this->publishableHelper->isGranted()) {
46
            $context['groups'][] = sprintf('%s:%s:write', $reflectionClass->getShortName(), PublishableLoader::GROUP_NAME);
47
        }
48
49
        return $context;
50
    }
51
}
52