Passed
Push — master ( 0d69f0...90ddb2 )
by Daniel
05:49
created

RoutableExtension::__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 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 4
ccs 0
cts 3
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\Doctrine\Extension\ORM;
15
16
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\ContextAwareQueryCollectionExtensionInterface;
17
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
18
use ApiPlatform\Core\Security\ResourceAccessCheckerInterface;
19
use Doctrine\ORM\QueryBuilder;
20
use Silverback\ApiComponentsBundle\Entity\Core\RoutableInterface;
21
22
/**
23
 * @author Daniel West <[email protected]>
24
 */
25
class RoutableExtension implements ContextAwareQueryCollectionExtensionInterface
26
{
27
    private ?string $securityStr;
28
    private ResourceAccessCheckerInterface $resourceAccessChecker;
29
30
    public function __construct(?string $securityStr, ResourceAccessCheckerInterface $resourceAccessChecker)
31
    {
32
        $this->securityStr = $securityStr;
33
        $this->resourceAccessChecker = $resourceAccessChecker;
34
    }
35
36
    public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null, array $context = []): void
37
    {
38
        if (!$this->securityStr) {
39
            return;
40
        }
41
42
        $refl = new \ReflectionClass($resourceClass);
43
        if (!$refl->implementsInterface(RoutableInterface::class)) {
44
            return;
45
        }
46
47
        if ($this->resourceAccessChecker->isGranted($resourceClass, $this->securityStr)) {
48
            return;
49
        }
50
51
        $alias = $queryBuilder->getRootAliases()[0];
52
        $queryBuilder
53
            ->andWhere(
54
                $queryBuilder->expr()->isNotNull("$alias.route_id")
55
            );
56
    }
57
}
58