View source
<?php
namespace Drupal\Core\Entity\Query\Sql;
use Drupal\Core\Entity\Query\QueryAggregateInterface;
class QueryAggregate extends Query implements QueryAggregateInterface {
protected $sqlExpressions = [];
public function execute() {
return $this
->prepare()
->addAggregate()
->compile()
->compileAggregate()
->addGroupBy()
->addSort()
->addSortAggregate()
->finish()
->result();
}
public function prepare() {
parent::prepare();
$this->sqlFields = [];
return $this;
}
public function conditionAggregateGroupFactory($conjunction = 'AND') {
$class = static::getClass($this->namespaces, 'ConditionAggregate');
return new $class($conjunction, $this, $this->namespaces);
}
public function existsAggregate($field, $function, $langcode = NULL) {
return $this->conditionAggregate
->exists($field, $function, $langcode);
}
public function notExistsAggregate($field, $function, $langcode = NULL) {
return $this->conditionAggregate
->notExists($field, $function, $langcode);
}
protected function addAggregate() {
if ($this->aggregate) {
foreach ($this->aggregate as $aggregate) {
$sql_field = $this
->getSqlField($aggregate['field'], $aggregate['langcode']);
$this->sqlExpressions[$aggregate['alias']] = $aggregate['function'] . "({$sql_field})";
}
}
return $this;
}
protected function compileAggregate() {
$this->conditionAggregate
->compile($this->sqlQuery);
return $this;
}
protected function addGroupBy() {
foreach ($this->groupBy as $group_by) {
$field = $group_by['field'];
$sql_field = $this
->getSqlField($field, $group_by['langcode']);
$this->sqlGroupBy[$sql_field] = $sql_field;
list($table, $real_sql_field) = explode('.', $sql_field);
$this->sqlFields[$sql_field] = [
$table,
$real_sql_field,
$this
->createSqlAlias($field, $real_sql_field),
];
}
return $this;
}
protected function addSortAggregate() {
if (!$this->count) {
foreach ($this->sortAggregate as $alias => $sort) {
$this->sqlQuery
->orderBy($alias, $sort['direction']);
}
}
return $this;
}
protected function finish() {
foreach ($this->sqlExpressions as $alias => $expression) {
$this->sqlQuery
->addExpression($expression, $alias);
}
return parent::finish();
}
public function createSqlAlias($field, $sql_field) {
$alias = str_replace('.', '_', $sql_field);
if (substr($alias, 0, 6) === 'field_' && substr($field, -6) !== '_value' && substr($alias, -6) === '_value') {
$alias = substr($alias, 0, -6);
}
return $alias;
}
protected function result() {
if ($this->count) {
return parent::result();
}
$return = [];
foreach ($this->sqlQuery
->execute() as $row) {
$return[] = (array) $row;
}
return $return;
}
}