ArrayDatasource: Apply a query's limit and offset when creating the result

This commit is contained in:
Johannes Meyer 2015-05-06 09:39:43 +02:00
parent d63381c002
commit f2ad2838f4
1 changed files with 11 additions and 22 deletions
library/Icinga/Data/DataArray

View File

@ -171,8 +171,11 @@ class ArrayDatasource implements Selectable
$columns = $query->getColumns(); $columns = $query->getColumns();
$filter = $query->getFilter(); $filter = $query->getFilter();
$offset = $query->hasOffset() ? $query->getOffset() : 0;
$limit = $query->hasLimit() ? $query->getLimit() : 0;
$foundStringKey = false; $foundStringKey = false;
$result = array(); $result = array();
$skipped = 0;
foreach ($this->data as $key => $row) { foreach ($this->data as $key => $row) {
if (is_string($key) && $this->keyColumn !== null && !isset($row->{$this->keyColumn})) { if (is_string($key) && $this->keyColumn !== null && !isset($row->{$this->keyColumn})) {
$row = clone $row; // Make sure that this won't affect the actual data $row = clone $row; // Make sure that this won't affect the actual data
@ -181,6 +184,9 @@ class ArrayDatasource implements Selectable
if (! $filter->matches($row)) { if (! $filter->matches($row)) {
continue; continue;
} elseif ($skipped < $offset) {
$skipped++;
continue;
} }
// Get only desired columns if asked so // Get only desired columns if asked so
@ -203,6 +209,10 @@ class ArrayDatasource implements Selectable
$foundStringKey |= is_string($key); $foundStringKey |= is_string($key);
$result[$key] = $filteredRow; $result[$key] = $filteredRow;
if (count($result) === $limit) {
break;
}
} }
// Sort the result // Sort the result
@ -220,27 +230,6 @@ class ArrayDatasource implements Selectable
return $this; return $this;
} }
/**
* Apply the limit, if any, of the given query to the current result and return the result
*
* @param SimpleQuery $query
*
* @return array
*/
protected function getLimitedResult(SimpleQuery $query)
{
if ($query->hasLimit()) {
if ($query->hasOffset()) {
$offset = $query->getOffset();
} else {
$offset = 0;
}
return array_slice($this->result, $offset, $query->getLimit());
} else {
return $this->result;
}
}
/** /**
* Return whether a query result exists * Return whether a query result exists
* *
@ -276,6 +265,6 @@ class ArrayDatasource implements Selectable
if (! $this->hasResult()) { if (! $this->hasResult()) {
$this->createResult($query); $this->createResult($query);
} }
return $this->getLimitedResult($query); return $this->result;
} }
} }