Chris@17
|
1 <?php
|
Chris@17
|
2
|
Chris@17
|
3 namespace Drupal\workspaces\EntityQuery;
|
Chris@17
|
4
|
Chris@17
|
5 use Drupal\Core\Entity\Query\Sql\Query as BaseQuery;
|
Chris@17
|
6
|
Chris@17
|
7 /**
|
Chris@17
|
8 * Alters entity queries to use a workspace revision instead of the default one.
|
Chris@17
|
9 */
|
Chris@17
|
10 class Query extends BaseQuery {
|
Chris@17
|
11
|
Chris@17
|
12 use QueryTrait {
|
Chris@17
|
13 prepare as traitPrepare;
|
Chris@17
|
14 }
|
Chris@17
|
15
|
Chris@17
|
16 /**
|
Chris@17
|
17 * Stores the SQL expressions used to build the SQL query.
|
Chris@17
|
18 *
|
Chris@17
|
19 * The array is keyed by the expression alias and the values are the actual
|
Chris@17
|
20 * expressions.
|
Chris@17
|
21 *
|
Chris@17
|
22 * @var array
|
Chris@17
|
23 * An array of expressions.
|
Chris@17
|
24 */
|
Chris@17
|
25 protected $sqlExpressions = [];
|
Chris@17
|
26
|
Chris@17
|
27 /**
|
Chris@17
|
28 * {@inheritdoc}
|
Chris@17
|
29 */
|
Chris@17
|
30 public function prepare() {
|
Chris@17
|
31 $this->traitPrepare();
|
Chris@17
|
32
|
Chris@17
|
33 // If the prepare() method from the trait decided that we need to alter this
|
Chris@17
|
34 // query, we need to re-define the the key fields for fetchAllKeyed() as SQL
|
Chris@17
|
35 // expressions.
|
Chris@17
|
36 if ($this->sqlQuery->getMetaData('active_workspace_id')) {
|
Chris@17
|
37 $id_field = $this->entityType->getKey('id');
|
Chris@17
|
38 $revision_field = $this->entityType->getKey('revision');
|
Chris@17
|
39
|
Chris@17
|
40 // Since the query is against the base table, we have to take into account
|
Chris@17
|
41 // that the revision ID might come from the workspace_association
|
Chris@17
|
42 // relationship, and, as a consequence, the revision ID field is no longer
|
Chris@17
|
43 // a simple SQL field but an expression.
|
Chris@17
|
44 $this->sqlFields = [];
|
Chris@17
|
45 $this->sqlExpressions[$revision_field] = "COALESCE(workspace_association.target_entity_revision_id, base_table.$revision_field)";
|
Chris@17
|
46 $this->sqlExpressions[$id_field] = "base_table.$id_field";
|
Chris@17
|
47 }
|
Chris@17
|
48
|
Chris@17
|
49 return $this;
|
Chris@17
|
50 }
|
Chris@17
|
51
|
Chris@17
|
52 /**
|
Chris@17
|
53 * {@inheritdoc}
|
Chris@17
|
54 */
|
Chris@17
|
55 protected function finish() {
|
Chris@17
|
56 foreach ($this->sqlExpressions as $alias => $expression) {
|
Chris@17
|
57 $this->sqlQuery->addExpression($expression, $alias);
|
Chris@17
|
58 }
|
Chris@17
|
59 return parent::finish();
|
Chris@17
|
60 }
|
Chris@17
|
61
|
Chris@17
|
62 }
|