Elgg  Version master
Metadata.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg\Database;
4 
13 
20 class Metadata extends Repository {
21 
25  public function count() {
27 
28  $count_expr = $this->options->distinct ? "DISTINCT {$qb->getTableAlias()}.id" : '*';
29  $qb->select("COUNT({$count_expr}) AS total");
30 
31  $qb = $this->buildQuery($qb);
32 
33  $result = _elgg_services()->db->getDataRow($qb);
34 
35  if (empty($result)) {
36  return 0;
37  }
38 
39  return (int) $result->total;
40  }
41 
52  public function calculate($function, $property, $property_type = null) {
53  if (!in_array(strtolower($function), QueryBuilder::CALCULATIONS)) {
54  throw new DomainException("'{$function}' is not a valid numeric function");
55  }
56 
57  if (!isset($property_type)) {
58  $property_type = 'metadata';
59  }
60 
62 
63  switch ($property_type) {
64  case 'attribute':
65  if (!in_array($property, \ElggEntity::PRIMARY_ATTR_NAMES)) {
66  throw new DomainException("'{$property}' is not a valid attribute");
67  }
68 
72  $alias = $qb->joinEntitiesTable($qb->getTableAlias(), 'entity_guid', 'inner', 'e');
73  $qb->addSelect("{$function}({$alias}.{$property}) AS calculation");
74  break;
75 
76  case 'metadata':
78  if (!empty($this->options->metadata_name_value_pairs) && $this->options->metadata_name_value_pairs[0]->names != $property) {
79  $alias = $qb->joinMetadataTable($qb->getTableAlias(), 'entity_guid', $property);
80  }
81 
82  $qb->addSelect("{$function}({$alias}.value) AS calculation");
83  break;
84 
85  case 'annotation':
86  $alias = $qb->joinAnnotationTable($qb->getTableAlias(), 'entity_guid', $property, 'inner', AnnotationsTable::DEFAULT_JOIN_ALIAS);
87  $qb->addSelect("{$function}({$alias}.value) AS calculation");
88  break;
89  }
90 
91  $qb = $this->buildQuery($qb);
92 
93  $result = _elgg_services()->db->getDataRow($qb);
94 
95  return $result ? (int) $result->calculation : 0;
96  }
97 
107  public function get($limit = null, $offset = null, $callback = null) {
109 
110  $distinct = $this->options->distinct ? 'DISTINCT ' : '';
111  $qb->select("{$distinct}{$qb->getTableAlias()}.*");
112 
113  $this->expandInto($qb, $qb->getTableAlias());
114 
115  $qb = $this->buildQuery($qb);
116 
117  // Keeping things backwards compatible
118  $original_order = elgg_extract('order_by', $this->options->__original_options);
119  if (empty($original_order) && $original_order !== false) {
120  $qb->addOrderBy("{$qb->getTableAlias()}.time_created", 'asc');
121  $qb->addOrderBy("{$qb->getTableAlias()}.id", 'asc');
122  }
123 
124  if ($limit > 0) {
125  $qb->setMaxResults((int) $limit);
126  $qb->setFirstResult((int) $offset);
127  }
128 
129  $callback = $callback ?: $this->options->callback;
130  if (!isset($callback)) {
131  $callback = function ($row) {
132  return new \ElggMetadata($row);
133  };
134  }
135 
136  return _elgg_services()->db->getData($qb, $callback);
137  }
138 
145  public function execute() {
146  if ($this->options->annotation_calculation) {
147  $clauses = $this->options->annotation_name_value_pairs;
148  if (count($clauses) > 1 && $this->options->annotation_name_value_pairs_operator !== 'OR') {
149  throw new LogicException('Annotation calculation can not be performed on multiple annotation name value pairs merged with AND');
150  }
151 
152  $clause = array_shift($clauses);
153 
154  return $this->calculate($this->options->annotation_calculation, $clause->names, 'annotation');
155  } else if ($this->options->metadata_calculation) {
156  $clauses = $this->options->metadata_name_value_pairs;
157  if (count($clauses) > 1 && $this->options->metadata_name_value_pairs_operator !== 'OR') {
158  throw new LogicException('Metadata calculation can not be performed on multiple metadata name value pairs merged with AND');
159  }
160 
161  $clause = array_shift($clauses);
162 
163  return $this->calculate($this->options->metadata_calculation, $clause->names, 'metadata');
164  } else if ($this->options->count) {
165  return $this->count();
166  } else if ($this->options->batch) {
167  return $this->batch($this->options->limit, $this->options->offset, $this->options->callback);
168  } else {
169  return $this->get($this->options->limit, $this->options->offset, $this->options->callback);
170  }
171  }
172 
180  protected function buildQuery(QueryBuilder $qb) {
181  $ands = [];
182 
183  foreach ($this->options->joins as $join) {
184  $join->prepare($qb, $qb->getTableAlias());
185  }
186 
187  foreach ($this->options->wheres as $where) {
188  $ands[] = $where->prepare($qb, $qb->getTableAlias());
189  }
190 
191  $ands[] = $this->buildPairedMetadataClause($qb, $this->options->metadata_name_value_pairs, $this->options->metadata_name_value_pairs_operator);
192  $ands[] = $this->buildEntityWhereClause($qb);
193  $ands[] = $this->buildPairedMetadataClause($qb, $this->options->search_name_value_pairs, 'OR');
194  $ands[] = $this->buildPairedAnnotationClause($qb, $this->options->annotation_name_value_pairs, $this->options->annotation_name_value_pairs_operator);
195  $ands[] = $this->buildPairedRelationshipClause($qb, $this->options->relationship_pairs);
196 
197  $ands = $qb->merge($ands);
198 
199  if (!empty($ands)) {
200  $qb->andWhere($ands);
201  }
202 
203  return $qb;
204  }
205 
215  // Even if all of these properties are empty, we want to add this clause regardless,
216  // to ensure that entity access clauses are appended to the query
217  $joined_alias = $qb->joinEntitiesTable($qb->getTableAlias(), 'entity_guid', 'inner', EntityTable::DEFAULT_JOIN_ALIAS);
218  return EntityWhereClause::factory($this->options)->prepare($qb, $joined_alias);
219  }
220 
231  protected function buildPairedMetadataClause(QueryBuilder $qb, $clauses, $boolean = 'AND') {
232  $parts = [];
233 
234  foreach ($clauses as $clause) {
235  $parts[] = $clause->prepare($qb, $qb->getTableAlias());
236  }
237 
238  return $qb->merge($parts, $boolean);
239  }
240 
251  protected function buildPairedAnnotationClause(QueryBuilder $qb, $clauses, $boolean = 'AND') {
252  $parts = [];
253 
254  foreach ($clauses as $clause) {
255  if (strtoupper($boolean) === 'OR' || count($clauses) === 1) {
256  $joined_alias = $qb->joinAnnotationTable($qb->getTableAlias(), 'entity_guid', null, 'inner', AnnotationsTable::DEFAULT_JOIN_ALIAS);
257  } else {
258  $joined_alias = $qb->joinAnnotationTable($qb->getTableAlias(), 'entity_guid', $clause->names);
259  }
260 
261  $parts[] = $clause->prepare($qb, $joined_alias);
262  }
263 
264  return $qb->merge($parts, $boolean);
265  }
266 
279  protected function buildPairedRelationshipClause(QueryBuilder $qb, $clauses, $boolean = 'AND') {
280  $parts = [];
281 
282  foreach ($clauses as $clause) {
283  if (strtoupper($boolean) === 'OR' || count($clauses) === 1) {
284  $joined_alias = $qb->joinRelationshipTable($qb->getTableAlias(), 'entity_guid', null, $clause->inverse, 'inner', RelationshipsTable::DEFAULT_JOIN_ALIAS);
285  } else {
286  $joined_alias = $qb->joinRelationshipTable($qb->getTableAlias(), 'entity_guid', $clause->names, $clause->inverse);
287  }
288 
289  $parts[] = $clause->prepare($qb, $joined_alias);
290  }
291 
292  return $qb->merge($parts, $boolean);
293  }
294 }
joinAnnotationTable(string $from_alias= '', string $from_column= 'guid', $name=null,?string $join_type= 'inner', string $joined_alias=null)
Join annotations table from alias and return joined table alias.
buildQuery(QueryBuilder $qb)
Build a database query.
Definition: Metadata.php:180
batch($limit=null, $offset=null, $callback=null)
Fetch rows as an ElggBatch.
Definition: Repository.php:123
const PRIMARY_ATTR_NAMES
Definition: ElggEntity.php:51
calculate($function, $property, $property_type=null)
Performs a mathematical calculation on metadata or metadata entity&#39;s properties.
Definition: Metadata.php:52
if(empty($count)) $offset
Definition: pagination.php:26
Exception thrown if a value does not adhere to a defined valid data domain.
buildEntityWhereClause(QueryBuilder $qb)
Process entity attribute wheres Joins entities table on entity guid in metadata table and applies whe...
Definition: Metadata.php:214
Database abstraction query builder.
elgg_extract($key, $array, $default=null, bool $strict=true)
Checks for $array[$key] and returns its value if it exists, else returns $default.
Definition: elgglib.php:254
Metadata repository contains methods for fetching metadata from database or performing calculations o...
Definition: Metadata.php:20
Abstract methods for interfacing with the database.
Definition: Repository.php:16
execute()
Execute the query resolving calculation, count and/or batch options.
Definition: Metadata.php:145
$limit
Definition: pagination.php:28
expandInto(QueryBuilder $qb, $table_alias=null)
Extend query builder with select, group_by, having and order_by clauses from $options.
Definition: Repository.php:250
buildPairedAnnotationClause(QueryBuilder $qb, $clauses, $boolean= 'AND')
Process annotation name value pairs Joins annotation table on entity_guid in the metadata table and a...
Definition: Metadata.php:251
Exception that represents error in the program logic.
joinEntitiesTable(string $from_alias= '', string $from_column= 'guid',?string $join_type= 'inner', string $joined_alias=null)
Join entity table from alias and return joined table alias.
joinRelationshipTable(string $from_alias= '', string $from_column= 'guid', $name=null, bool $inverse=false,?string $join_type= 'inner', string $joined_alias=null)
Join relationship table from alias and return joined table alias.
static fromTable($table, $alias=null)
{}
Definition: Select.php:13
getTableAlias()
Returns the alias of the primary table.
merge($parts=null, $boolean= 'AND')
Merges multiple composite expressions with a boolean.
buildPairedRelationshipClause(QueryBuilder $qb, $clauses, $boolean= 'AND')
Process relationship name value pairs Joins relationship table on entity_guid in the metadata table a...
Definition: Metadata.php:279
_elgg_services()
Get the global service provider.
Definition: elgglib.php:346
$qb
Definition: queue.php:12
buildPairedMetadataClause(QueryBuilder $qb, $clauses, $boolean= 'AND')
Process metadata name value pairs Applies where clauses to the selected metadata table.
Definition: Metadata.php:231