|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the Sylius package. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Paweł Jędrzejewski |
|
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 Sylius\Bundle\ApiBundle\Doctrine\QueryCollectionExtension; |
|
15
|
|
|
|
|
16
|
|
|
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\ContextAwareQueryCollectionExtensionInterface; |
|
17
|
|
|
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface; |
|
18
|
|
|
use Doctrine\ORM\QueryBuilder; |
|
19
|
|
|
use Sylius\Bundle\ApiBundle\Context\UserContextInterface; |
|
20
|
|
|
use Sylius\Bundle\ApiBundle\Serializer\ContextKeys; |
|
21
|
|
|
use Sylius\Component\Core\Model\ProductInterface; |
|
22
|
|
|
use Webmozart\Assert\Assert; |
|
23
|
|
|
|
|
24
|
|
|
final class ProductsByChannelAndLocaleCodeExtension implements ContextAwareQueryCollectionExtensionInterface |
|
25
|
|
|
{ |
|
26
|
|
|
/** @var UserContextInterface */ |
|
27
|
|
|
private $userContext; |
|
28
|
|
|
|
|
29
|
|
|
public function __construct(UserContextInterface $userContext) |
|
30
|
|
|
{ |
|
31
|
|
|
$this->userContext = $userContext; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
public function applyToCollection( |
|
35
|
|
|
QueryBuilder $queryBuilder, |
|
36
|
|
|
QueryNameGeneratorInterface $queryNameGenerator, |
|
37
|
|
|
string $resourceClass, |
|
38
|
|
|
string $operationName = null, |
|
39
|
|
|
array $context = [] |
|
40
|
|
|
): void { |
|
41
|
|
|
if (!is_a($resourceClass, ProductInterface::class, true)) { |
|
42
|
|
|
return; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
$user = $this->userContext->getUser(); |
|
46
|
|
|
if ($user !== null && in_array('ROLE_API_ACCESS', $user->getRoles(), true)) { |
|
47
|
|
|
return; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
Assert::keyExists($context, ContextKeys::CHANNEL); |
|
51
|
|
|
Assert::keyExists($context, ContextKeys::LOCALE_CODE); |
|
52
|
|
|
|
|
53
|
|
|
$channel = $context[ContextKeys::CHANNEL]; |
|
54
|
|
|
$localeCode = $context[ContextKeys::LOCALE_CODE]; |
|
55
|
|
|
|
|
56
|
|
|
$rootAlias = $queryBuilder->getRootAliases()[0]; |
|
57
|
|
|
$queryBuilder |
|
58
|
|
|
->addSelect('translation') |
|
59
|
|
|
->innerJoin(sprintf('%s.translations', $rootAlias), 'translation', 'WITH', 'translation.locale = :localeCode') |
|
60
|
|
|
->andWhere(sprintf(':channel MEMBER OF %s.channels', $rootAlias)) |
|
61
|
|
|
->setParameter('channel', $channel) |
|
62
|
|
|
->setParameter('localeCode', $localeCode) |
|
63
|
|
|
; |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|