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

RoutableExtension   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 30
ccs 0
cts 15
cp 0
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A applyToCollection() 0 19 4
A __construct() 0 4 1
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