/** * Gets the grouping that groups everything in an array. * * @param string $field */ private function getGroup($field) { $group = new Group(); $group->setGroupBy('_id'); $condition = Condition::getConditionByIfArray(['$gte' => ['$' . $field, []]], '$' . $field . '_unwrapped', '$' . $field . '_original'); $push = new Push(); $push->setPush($condition); $group->setResultField($field, $push); return $group; }
/** * Adds the ranges projection * Ranges array should hold array with label, min and / or max (at least one of min and max is required). * * @param string $field * @param array $ranges */ public function addRange($field, array $ranges) { $conditions = []; foreach ($ranges as $range) { $condition = Condition::getConditionByIfArray(self::getMinMaxExpression($field, $range), $range['label'], '$' . $field); $conditions[] = $condition; } $projectionCondition = array_pop($conditions); while ($nextCondition = array_pop($conditions)) { $nextCondition->setElse($projectionCondition); $projectionCondition = $nextCondition; } $this->includeOperationField($field, $projectionCondition); }
/** * Test if fields are added. */ public function testFieldsAreAdded() { $testData = [['foo' => 'foo'], ['foo' => 'foo'], ['foo' => 'bar'], ['foo' => 'bar'], ['foo' => 'bar']]; foreach ($testData as $test) { $this->collection->save($test); } $projection = new Projection(); $projection->includeField('foo'); $condition = Condition::getConditionByIfArray(['$eq' => ['$foo', 'foo']], true, false); $projection->includeOperationField('isFoo', $condition); $result = $this->collection->aggregate([$projection->getStage()]); $this->assertEquals(5, count($result['result'])); foreach ($result['result'] as $res) { if ($res['foo'] === 'foo') { $this->assertTrue($res['isFoo']); } else { $this->assertFalse($res['isFoo']); } } }
/** * Gets test data. */ public function providePushTestData() { return [['$foo', ['$push' => '$foo']], [Condition::getConditionByIfArray(['$eq' => ['$foo', 'foo']], true, false), ['$push' => ['$cond' => [['$eq' => ['$foo', 'foo']], true, false]]]]]; }
/** * Gets test data. */ public function provideSumTestData() { return [[1, ['$sum' => 1]], [Condition::getConditionByIfArray(['$eq' => ['$foo', 'foo']], 1, 2), ['$sum' => ['$cond' => [['$eq' => ['$foo', 'foo']], 1, 2]]]]]; }
/** * Gets test data. */ public function provideConditionTestData() { $testCondition = Condition::getConditionByIfArray(['$eq' => ['$foo', 'foo']], true, false); return [[['if' => ['$eq' => ['$foo', 'foo']], 'then' => true, 'else' => false], ['$cond' => [['$eq' => ['$foo', 'foo']], true, false]]], [['if' => ['$eq' => ['$foo', 'foo']], 'then' => $testCondition, 'else' => false], ['$cond' => [['$eq' => ['$foo', 'foo']], ['$cond' => [['$eq' => ['$foo', 'foo']], true, false]], false]]], [['if' => ['$eq' => ['$foo', 'foo']], 'then' => true, 'else' => $testCondition], ['$cond' => [['$eq' => ['$foo', 'foo']], true, ['$cond' => [['$eq' => ['$foo', 'foo']], true, false]]]]]]; }