Passed
Pull Request — feature/publishable (#43)
by Vincent
08:57 queued 02:27
created

PublishableContextBuilder::classHasSerializerGroupsOnProperties()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 5
c 1
b 0
f 1
dl 0
loc 10
ccs 0
cts 6
cp 0
rs 10
cc 3
nc 3
nop 1
crap 12
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;
15
16
use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;
17
use Silverback\ApiComponentBundle\Publishable\PublishableHelper;
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
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
    private ClassMetadataFactoryInterface $classMetadataFactory;
29
30
    public function __construct(SerializerContextBuilderInterface $decorated, PublishableHelper $publishableHelper, ClassMetadataFactoryInterface $classMetadataFactory)
31
    {
32
        $this->decorated = $decorated;
33
        $this->publishableHelper = $publishableHelper;
34
        $this->classMetadataFactory = $classMetadataFactory;
35
    }
36
37
    public function createFromRequest(Request $request, bool $normalization, array $extractedAttributes = null): array
38
    {
39
        $context = $this->decorated->createFromRequest($request, $normalization, $extractedAttributes);
40
        if (empty($resourceClass = $context['resource_class']) || empty($context['groups'])) {
41
            return $context;
42
        }
43
44
        $reflectionClass = new \ReflectionClass($resourceClass);
45
        if ($normalization) {
46
            $context['groups'][] = sprintf('%s:publishable:read', $reflectionClass->getShortName());
47
        } elseif ($this->publishableHelper->isGranted()) {
48
            $context['groups'][] = sprintf('%s:publishable:write', $reflectionClass->getShortName());
49
        }
50
51
        return $context;
52
    }
53
}
54