Skip to content

Commit

Permalink
Added indexBy to QueryBuilder.
Browse files Browse the repository at this point in the history
  • Loading branch information
TCB13 committed Mar 5, 2019
1 parent 4dece27 commit 7f5cb92
Showing 1 changed file with 28 additions and 6 deletions.
34 changes: 28 additions & 6 deletions src/QueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ class QueryBuilder
private $lookup = [];
private $unwind = [];
private $group = [];
private $indexBy = null;

private $expectedMultipleResults = true;

Expand Down Expand Up @@ -161,12 +162,14 @@ public function select($fields): self
return true;
});

if (count($this->fields))
if (count($this->fields)) {
$this->fields = call_user_func_array("array_merge", $this->fields);
}

// Exclude built in _id if not set in fields - MongoDB always returns this by default
if (!in_array("_id", $fields))
if (!in_array("_id", $fields)) {
$this->fields["_id"] = 0;
}

return $this;
}
Expand Down Expand Up @@ -467,16 +470,22 @@ protected function deserializeResult($array = "array", $document = "array", $roo

if ($this->deserializeMongoIds && array_key_exists("_id", $this->fields) && $this->fields["_id"] === 1) {
$results = \array_map(function ($result) {
if (is_object($result))
if (is_object($result)) {
$result->_id = (string)$result->_id;
else
}
else {
$result["_id"] = (string)$result["_id"];
}
return $result;
}, $results);
}

if ($this->expectedMultipleResults)
if ($this->expectedMultipleResults) {
if ($this->indexBy !== null) {
$results = array_combine(array_column($results, $this->indexBy), $results);
}
return $results;
}

return empty($results) ? null : $results[0];
}
Expand All @@ -496,6 +505,20 @@ public function toJson(): string
return json_encode($this->toArray());
}

public function indexBy(string $property)
{
if (!$this->expectedMultipleResults) {
throw new Exception("You can only use indexBy with findAll.");
}

if (!empty($this->fields) && !array_key_exists($property, $this->fields)) {
throw new Exception("Property '{$property}' not selected.");
}

$this->indexBy = $property;
return $this;
}

/**
* Takes a variable number of QueryBuilder instances and merges them into one.
*
Expand All @@ -505,7 +528,6 @@ public function toJson(): string
*/
public static function merge(QueryBuilder ...$queryBuilderInstances): self
{

$merge = [
"fields",
"filters",
Expand Down

0 comments on commit 7f5cb92

Please sign in to comment.