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