Skip to content

Commit

Permalink
feat: add site restriction for api
Browse files Browse the repository at this point in the history
  • Loading branch information
twojtylak committed Nov 28, 2022
1 parent f0b1347 commit 4182c5e
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class ApiRestrictionContainer extends AbstractRestrictionContainer
protected $defaultRestrictionTypes = [
DeletedRestriction::class,
LanguageRestriction::class,
SiteRestriction::class,
];

/**
Expand Down
68 changes: 68 additions & 0 deletions Classes/Database/Query/Restriction/SiteRestriction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php

declare(strict_types=1);

namespace DFAU\ToujouApi\Database\Query\Restriction;

use Psr\Http\Message\RequestInterface;
use TYPO3\CMS\Core\Database\Query\Expression\CompositeExpression;
use TYPO3\CMS\Core\Database\Query\Expression\ExpressionBuilder;
use TYPO3\CMS\Core\Database\Query\Restriction\QueryRestrictionInterface;
use TYPO3\CMS\Core\Database\QueryGenerator;
use TYPO3\CMS\Core\Site\Entity\Site;

class SiteRestriction implements QueryRestrictionInterface
{
/** @var QueryGenerator */
private $queryGenerator;

/** @var null|int[] */
private $cachedSitePids;

public function __construct(QueryGenerator $queryGenerator)
{
$this->queryGenerator = $queryGenerator;
}

public function buildExpression(array $queriedTables, ExpressionBuilder $expressionBuilder): CompositeExpression
{
$constraints = [];

$sitePids = $this->getSitePids();

if ([] === $sitePids) {
return $expressionBuilder->andX();
}

foreach ($queriedTables as $tableAlias => $tableName) {
$constraints[] = $expressionBuilder->in($tableAlias . '.pid', $sitePids);
}

return $expressionBuilder->andX(...$constraints);
}

private function getSitePids(): array
{
if (\is_array($this->cachedSitePids)) {
return $this->cachedSitePids;
}

/** @var RequestInterface $request */
$request = $GLOBALS['TYPO3_REQUEST'] ?? null;

if (null === $request) {
return [];
}

/** @var Site $site */
$site = $request->getAttribute('site');

if (null === $site) {
return [];
}

$this->cachedSitePids = \explode(',', $this->queryGenerator->getTreeList($site->getRootPageId(), 999));

return $this->cachedSitePids;
}
}
3 changes: 3 additions & 0 deletions Configuration/Services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,6 @@ services:

DFAU\ToujouApi\Database\Query\Restriction\LanguageRestriction:
public: true

DFAU\ToujouApi\Database\Query\Restriction\SiteRestriction:
public: true

0 comments on commit 4182c5e

Please sign in to comment.