Skip to content

Commit 301cfd7

Browse files
committed
Merge pull request #787 from LearningLocker/issue/aggregationTypes
Allows ISODates in the aggregation API
2 parents e540f2a + afe278d commit 301cfd7

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

app/controllers/api/Statements.php

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
<?php namespace Controllers\API;
22

3+
use Carbon\Carbon;
34
use \Locker\Repository\Query\QueryRepository as QueryRepository;
45
use \Locker\Helpers\Exceptions as Exceptions;
56

@@ -29,7 +30,7 @@ public function where() {
2930
* @return Aggregate http://php.net/manual/en/mongocollection.aggregate.php#refsect1-mongocollection.aggregate-examples
3031
*/
3132
public function aggregate() {
32-
$pipeline = $this->getParam('pipeline');
33+
$pipeline = $this->getPipeline();
3334
return \Response::json($this->query->aggregate($this->getOptions(), $pipeline));
3435
}
3536

@@ -82,9 +83,43 @@ public function void() {
8283
return \Response::json($this->query->void($match, $this->getOptions()));
8384
}
8485

86+
private function convertDte($value) {
87+
if(is_array($value)) {
88+
if(isset($value['$dte'])) {
89+
$date = $value['$dte'];
90+
$parsedDate = new Carbon($date);
91+
if($parsedDate) return new \MongoDate($parsedDate->timestamp, $parsedDate->micro);
92+
else throw new Exceptions\Exception("`$date` is not a valid date.");
93+
}
94+
else
95+
return array_map([$this, __FUNCTION__], $value); // recursively apply this function to whole pipeline
96+
}
97+
98+
return $value;
99+
}
100+
101+
private function convertOid($value) {
102+
if(is_array($value)) {
103+
if(isset($value['$oid']))
104+
return new \MongoId($value['$oid']);
105+
else
106+
return array_map([$this, __FUNCTION__], $value); // recursively apply this function to whole pipeline
107+
}
108+
109+
return $value;
110+
}
111+
112+
private function getPipeline() {
113+
$pipeline = $this->getParam('pipeline');
114+
$pipeline = $this->convertDte($pipeline);
115+
$pipeline = $this->convertOid($pipeline);
116+
return $pipeline;
117+
}
118+
85119
private function getParam($param) {
86120
$param_value = \LockerRequest::getParam($param);
87121
$value = json_decode($param_value, true);
122+
88123
if ($value === null && $param_value === null) {
89124
throw new Exceptions\Exception("Expected `$param` to be defined as a URL parameter.");
90125
} else if ($value === null) {

0 commit comments

Comments
 (0)