Passed
Pull Request — master (#61)
by Daniel
06:02
created

PublishableExtension::applyToItem()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 35
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 19
nc 5
nop 6
dl 0
loc 35
ccs 0
cts 19
cp 0
crap 42
rs 9.0111
c 0
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\Extension\QueryItemExtensionInterface;
18
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
19
use Doctrine\ORM\EntityRepository;
20
use Doctrine\ORM\QueryBuilder;
21
use Doctrine\Persistence\ManagerRegistry;
22
use Silverback\ApiComponentsBundle\Annotation\Publishable;
23
use Silverback\ApiComponentsBundle\Helper\Publishable\PublishableHelper;
24
use Symfony\Component\HttpFoundation\RequestStack;
25
26
/**
27
 * @author Vincent Chalamon <[email protected]>
28
 */
29
final class PublishableExtension implements QueryItemExtensionInterface, ContextAwareQueryCollectionExtensionInterface
30
{
31
    private PublishableHelper $publishableHelper;
32
    private RequestStack $requestStack;
33
    private ManagerRegistry $registry;
34
    private ?Publishable $configuration = null;
35
36
    public function __construct(PublishableHelper $publishableHelper, RequestStack $requestStack, ManagerRegistry $registry)
37
    {
38
        $this->publishableHelper = $publishableHelper;
39
        $this->requestStack = $requestStack;
40
        $this->registry = $registry;
41
    }
42
43
    public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, string $operationName = null, array $context = []): void
44
    {
45
        $configuration = $this->getConfiguration($resourceClass);
46
47
        if (!$configuration || !$this->requestStack->getCurrentRequest()) {
48
            return;
49
        }
50
51
        if (!$this->isDraftRequest($resourceClass, $context)) {
52
            // User has no access to draft object
53
            $this->updateQueryBuilderForUnauthorizedUsers($queryBuilder, $configuration);
54
55
            return;
56
        }
57
58
        $alias = $queryBuilder->getRootAliases()[0];
59
60
        // (o.publishedResource = :id OR o.id = :id) ORDER BY o.publishedResource IS NULL LIMIT 1
61
        $criteriaReset = false;
62
        foreach ($identifiers as $identifier => $value) {
63
            $predicates = $queryBuilder->expr()->orX($queryBuilder->expr()->eq("$alias.$configuration->associationName", ":id_$identifier"), $queryBuilder->expr()->eq("$alias.$identifier", ":id_$identifier"), );
64
65
            // Reset queryBuilder to prevent an invalid DQL
66
            if (!$criteriaReset) {
67
                $queryBuilder->where($predicates);
68
                $criteriaReset = true;
69
            } else {
70
                $queryBuilder->andWhere($predicates);
71
            }
72
            $queryBuilder->setParameter("id_$identifier", $value);
73
        }
74
75
        $queryBuilder->addSelect("CASE WHEN $alias.$configuration->associationName IS NULL THEN 1 ELSE 0 END AS HIDDEN assocNameSort");
76
        $queryBuilder->orderBy('assocNameSort', 'ASC');
77
        $queryBuilder->setMaxResults(1);
78
    }
79
80
    public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null, array $context = []): void
81
    {
82
        if (!$configuration = $this->getConfiguration($resourceClass)) {
83
            return;
84
        }
85
86
        if (!$this->isDraftRequest($resourceClass, $context)) {
87
            // User has no access to draft object
88
            $this->updateQueryBuilderForUnauthorizedUsers($queryBuilder, $configuration);
89
90
            return;
91
        }
92
93
        $alias = $queryBuilder->getRootAliases()[0];
94
        $identifiers = $this->registry->getManagerForClass($resourceClass)->getClassMetadata($resourceClass)->getIdentifier();
95
        $dql = $this->getDQL($configuration, $resourceClass);
96
97
        // o.id NOT IN (SELECT p.publishedResource FROM {table} t WHERE t.publishedResource IS NOT NULL)
98
        foreach ($identifiers as $identifier) {
99
            $queryBuilder->andWhere($queryBuilder->expr()->notIn("$alias.$identifier", $dql));
100
        }
101
    }
102
103
    private function getDQL(Publishable $configuration, string $resourceClass): string
104
    {
105
        /** @var EntityRepository $repository */
106
        $repository = $this->registry->getManagerForClass($resourceClass)->getRepository($resourceClass);
107
        $queryBuilder = $repository->createQueryBuilder('o2');
108
109
        return $queryBuilder
110
            ->select("IDENTITY(o2.$configuration->associationName)")
111
            ->where($queryBuilder->expr()->isNotNull("o2.$configuration->associationName"))
112
            ->getDQL();
113
    }
114
115
    private function isDraftRequest(string $resourceClass, array $context): bool
116
    {
117
        return $this->publishableHelper->isGranted($resourceClass) && false === ($context['filters']['published'] ?? false);
118
    }
119
120
    private function updateQueryBuilderForUnauthorizedUsers(QueryBuilder $queryBuilder, Publishable $configuration): void
121
    {
122
        $alias = $queryBuilder->getRootAliases()[0];
123
        $queryBuilder
124
            ->andWhere("$alias.$configuration->fieldName IS NOT NULL")
125
            ->andWhere("$alias.$configuration->fieldName <= :currentTime")
126
            ->setParameter('currentTime', new \DateTimeImmutable());
127
    }
128
129
    private function getConfiguration(string $resourceClass): ?Publishable
130
    {
131
        if (!$this->configuration && ($this->publishableHelper->getAnnotationReader()->isConfigured($resourceClass))) {
132
            $this->configuration = $this->publishableHelper->getAnnotationReader()->getConfiguration($resourceClass);
133
        }
134
135
        return $this->configuration;
136
    }
137
}
138