Passed
Push — master ( da4d4a...daa4ed )
by Angel Fernando Quiroz
08:01
created

PageExtension   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 35
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A applyToCollection() 0 8 1
A addWhere() 0 18 3
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
declare(strict_types=1);
6
7
namespace Chamilo\CoreBundle\DataProvider\Extension;
8
9
use ApiPlatform\Doctrine\Orm\Extension\QueryCollectionExtensionInterface;
10
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
11
use ApiPlatform\Metadata\Operation;
12
use Chamilo\CoreBundle\Entity\Page;
13
use Chamilo\CoreBundle\ServiceHelper\AccessUrlHelper;
14
use Doctrine\ORM\QueryBuilder;
15
use Symfony\Bundle\SecurityBundle\Security;
16
17
final class PageExtension implements QueryCollectionExtensionInterface // , QueryItemExtensionInterface
18
{
19
    public function __construct(
20
        private readonly Security $security,
21
        private readonly AccessUrlHelper $accessUrlHelper,
22
    ) {}
23
24
    public function applyToCollection(
25
        QueryBuilder $queryBuilder,
26
        QueryNameGeneratorInterface $queryNameGenerator,
27
        string $resourceClass,
28
        ?Operation $operation = null,
29
        array $context = []
30
    ): void {
31
        $this->addWhere($queryBuilder, $resourceClass);
32
    }
33
34
    private function addWhere(QueryBuilder $qb, string $resourceClass): void
35
    {
36
        if (Page::class !== $resourceClass) {
37
            return;
38
        }
39
40
        $alias = $qb->getRootAliases()[0];
41
42
        $url = $this->accessUrlHelper->getCurrent();
43
44
        // Url filter by default.
45
        $qb
46
            ->andWhere("$alias.url = :url")
47
            ->setParameter('url', $url->getId())
48
        ;
49
50
        if (!$this->security->isGranted('ROLE_ADMIN')) {
51
            $qb->andWhere("$alias.enabled = 1");
52
        }
53
    }
54
}
55