Passed
Push — master ( 1ff3a3...7caafd )
by Daniel
06:46
created

ComponentPositionContextBuilder::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 5
ccs 0
cts 4
cp 0
crap 2
rs 10
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\Entity\Core\ComponentPosition;
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
20
use Symfony\Component\Security\Core\Security;
21
22
/**
23
 * @author Daniel West <[email protected]>
24
 */
25
final class ComponentPositionContextBuilder implements SerializerContextBuilderInterface
26
{
27
    private SerializerContextBuilderInterface $decorated;
28
    private RoleHierarchyInterface $roleHierarchy;
29
    private Security $security;
30
31
    public function __construct(SerializerContextBuilderInterface $decorated, RoleHierarchyInterface $roleHierarchy, Security $security)
32
    {
33
        $this->decorated = $decorated;
34
        $this->roleHierarchy = $roleHierarchy;
35
        $this->security = $security;
36
    }
37
38
    public function createFromRequest(Request $request, bool $normalization, array $extractedAttributes = null): array
39
    {
40
        $context = $this->decorated->createFromRequest($request, $normalization, $extractedAttributes);
41
        if (ComponentPosition::class !== $context['resource_class']) {
42
            return $context;
43
        }
44
        $rw = $normalization ? 'read' : 'write';
45
        $context['groups'][] = sprintf('ComponentPosition:%s', $rw);
46
        $user = $this->security->getUser();
47
        if ($user) {
48
            $reachableRoles = $this->roleHierarchy->getReachableRoleNames($user->getRoles());
49
            foreach ($reachableRoles as $reachableRole) {
50
                $context['groups'][] = sprintf('ComponentPosition:%s:%s', $rw, strtolower($reachableRole));
51
            }
52
        }
53
54
        return $context;
55
    }
56
}
57