Passed
Push — master ( 11fb90...557bd4 )
by Daniel
05:22
created

PublishableContextBuilder::createFromRequest()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
cc 7
eloc 15
nc 5
nop 3
dl 0
loc 24
ccs 0
cts 15
cp 0
crap 56
rs 8.8333
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\Helper\Publishable\PublishableStatusChecker;
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 PublishableStatusChecker $publishableStatusChecker;
28
29
    public function __construct(SerializerContextBuilderInterface $decorated, PublishableStatusChecker $publishableStatusChecker)
30
    {
31
        $this->decorated = $decorated;
32
        $this->publishableStatusChecker = $publishableStatusChecker;
33
    }
34
35
    public function createFromRequest(Request $request, bool $normalization, array $extractedAttributes = null): array
36
    {
37
        $context = $this->decorated->createFromRequest($request, $normalization, $extractedAttributes);
38
39
        if (
40
            empty($resourceClass = $context['resource_class']) ||
41
            empty($context['groups']) ||
42
            !$this->publishableStatusChecker->getAnnotationReader()->isConfigured($resourceClass)
43
        ) {
44
            return $context;
45
        }
46
47
        $reflectionClass = new \ReflectionClass($resourceClass);
48
        $isAuthorized = $this->publishableStatusChecker->isGranted($resourceClass);
49
        if ($normalization) {
50
            $context['groups'][] = sprintf('%s:%s:read', $reflectionClass->getShortName(), PublishableLoader::GROUP_NAME);
51
            if ($isAuthorized) {
52
                $context['groups'][] = sprintf('%s:%s:read:authorized', $reflectionClass->getShortName(), PublishableLoader::GROUP_NAME);
53
            }
54
        } elseif ($isAuthorized) {
55
            $context['groups'][] = sprintf('%s:%s:write', $reflectionClass->getShortName(), PublishableLoader::GROUP_NAME);
56
        }
57
58
        return $context;
59
    }
60
}
61