Passed
Push — master ( 3ec415...9f2f47 )
by Daniel
16:25
created

RouteExtension::__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
nc 1
nop 2
dl 0
loc 4
ccs 0
cts 3
cp 0
crap 2
rs 10
c 1
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\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
21
/**
22
 * @author Daniel West <[email protected]>
23
 */
24
class RouteExtension implements ContextAwareQueryCollectionExtensionInterface
25
{
26
    private ?array $config;
27
    private ResourceAccessCheckerInterface $resourceAccessChecker;
28
29
    public function __construct(?array $config, ResourceAccessCheckerInterface $resourceAccessChecker)
30
    {
31
        $this->config = $config;
32
        $this->resourceAccessChecker = $resourceAccessChecker;
33
    }
34
35
    public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null, array $context = []): void
36
    {
37
        if (!$this->config) {
38
            return;
39
        }
40
        $alias = $queryBuilder->getRootAliases()[0];
41
        foreach ($this->config as $index => $routeConfig) {
42
            if ($this->resourceAccessChecker->isGranted($resourceClass, $routeConfig['security'])) {
43
                continue;
44
            }
45
            $param = 'path_' . $index;
46
            $queryBuilder
47
                ->andWhere(
48
                    $queryBuilder->expr()->notLike("$alias.path", ':' . $param)
49
                );
50
            $queryBuilder->setParameter($param, str_replace('*', '%', $routeConfig['route']));
51
        }
52
    }
53
}
54