Passed
Push — feature/uploadable ( 7c6d25...a7ed20 )
by Daniel
11:07
created

PublishableContextBuilder::createFromRequest()   A

Complexity

Conditions 6
Paths 4

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 12
nc 4
nop 3
dl 0
loc 19
ccs 0
cts 12
cp 0
crap 42
rs 9.2222
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Components 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\ApiComponentsBundle\Serializer\ContextBuilder;
15
16
use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;
17
use Silverback\ApiComponentsBundle\Publishable\PublishableHelper;
18
use Silverback\ApiComponentsBundle\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 (
39
            empty($resourceClass = $context['resource_class']) ||
40
            empty($context['groups']) ||
41
            !$this->publishableHelper->getAnnotationReader()->isConfigured($resourceClass)
42
        ) {
43
            return $context;
44
        }
45
46
        $reflectionClass = new \ReflectionClass($resourceClass);
47
        if ($normalization) {
48
            $context['groups'][] = sprintf('%s:%s:read', $reflectionClass->getShortName(), PublishableLoader::GROUP_NAME);
49
        } elseif ($this->publishableHelper->isGranted($resourceClass)) {
50
            $context['groups'][] = sprintf('%s:%s:write', $reflectionClass->getShortName(), PublishableLoader::GROUP_NAME);
51
        }
52
53
        return $context;
54
    }
55
}
56