0223e9a2291618fe102e71f8fd8f4a4d2ff41c60
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Database / Query / Restriction / BackendWorkspaceRestriction.php
1 <?php
2 declare (strict_types = 1);
3 namespace TYPO3\CMS\Core\Database\Query\Restriction;
4
5 /*
6 * This file is part of the TYPO3 CMS project.
7 *
8 * It is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, either version 2
10 * of the License, or any later version.
11 *
12 * For the full copyright and license information, please read the
13 * LICENSE.txt file that was distributed with this source code.
14 *
15 * The TYPO3 project - inspiring people to share!
16 */
17
18 use TYPO3\CMS\Core\Database\Query\Expression\CompositeExpression;
19 use TYPO3\CMS\Core\Database\Query\Expression\ExpressionBuilder;
20 use TYPO3\CMS\Core\Versioning\VersionState;
21
22 /**
23 * Restriction to make queries in TYPO3 backend context versioning/ workspace aware
24 */
25 class BackendWorkspaceRestriction implements QueryRestrictionInterface
26 {
27 /**
28 * @var int
29 */
30 protected $workspaceId;
31
32 /**
33 * @var bool
34 */
35 protected $includeRowsForWorkspaceOverlay;
36
37 /**
38 * @param int $workspaceId
39 * @param bool $includeRowsForWorkspaceOverlay
40 */
41 public function __construct(int $workspaceId = null, $includeRowsForWorkspaceOverlay = true)
42 {
43 $this->workspaceId = $workspaceId === null ? $GLOBALS['BE_USER']->workspace : $workspaceId;
44 $this->includeRowsForWorkspaceOverlay = $includeRowsForWorkspaceOverlay;
45 }
46
47 /**
48 * Main method to build expressions for given tables
49 *
50 * @param array $queriedTables Array of tables, where array key is table name and value potentially an alias
51 * @param ExpressionBuilder $expressionBuilder Expression builder instance to add restrictions with
52 * @return CompositeExpression The result of query builder expression(s)
53 */
54 public function buildExpression(array $queriedTables, ExpressionBuilder $expressionBuilder): CompositeExpression
55 {
56 $constraints = [];
57 foreach ($queriedTables as $tableName => $tableAlias) {
58 $workspaceEnabled = $GLOBALS['TCA'][$tableName]['ctrl']['versioningWS'] ?? null;
59 if (!empty($workspaceEnabled)) {
60 $tablePrefix = $tableAlias ?: $tableName;
61 $workspaceIdExpression = $expressionBuilder->eq(
62 $tablePrefix . '.t3ver_wsid',
63 (int)$this->workspaceId
64 );
65 if ($this->includeRowsForWorkspaceOverlay) {
66 $constraints[] = $expressionBuilder->orX(
67 $workspaceIdExpression,
68 $expressionBuilder->lte(
69 $tablePrefix . '.t3ver_state',
70 new VersionState(VersionState::DEFAULT_STATE)
71 )
72 );
73 } else {
74 $comparisonExpression = $this->workspaceId === 0 ? 'neq' : 'eq';
75 $constraints[] = $workspaceIdExpression;
76 $constraints[] = $expressionBuilder->{$comparisonExpression}(
77 $tablePrefix . '.pid',
78 -1
79 );
80 }
81 }
82 }
83 return $expressionBuilder->andX(...$constraints);
84 }
85 }