Skip to content

Commit

Permalink
Merge pull request #53 from alcaeus/fix-map-reduce-queries
Browse files Browse the repository at this point in the history
Ensure mapReduce queries with empty map work
  • Loading branch information
alcaeus committed Feb 10, 2016
2 parents 662a8c0 + 7356283 commit 489af35
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 2 deletions.
9 changes: 7 additions & 2 deletions lib/Alcaeus/MongoDbAdapter/TypeConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public static function fromLegacy($value)
$result[$key] = self::fromLegacy($item);
}

return self::ensureCorrectType($result);
return self::ensureCorrectType($result, is_object($value));
default:
return $value;
}
Expand Down Expand Up @@ -143,10 +143,15 @@ private static function convertBSONObjectToLegacy(BSON\Type $value)
* Converts all arrays with non-numeric keys to stdClass
*
* @param array $array
* @param bool $wasObject
* @return array|Model\BSONArray|Model\BSONDocument
*/
private static function ensureCorrectType(array $array)
private static function ensureCorrectType(array $array, $wasObject = false)
{
if ($array === [] && $wasObject) {
return (object) $array;
}

if (static::isNumericArray($array)) {
return $array;
}
Expand Down
74 changes: 74 additions & 0 deletions tests/Alcaeus/MongoDbAdapter/MongoCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -997,6 +997,80 @@ public function testGroup()
);
}

public function testMapReduce()
{
$data = array(
array(
'username' => 'jones',
'likes' => 20.0,
'text' => 'Hello world!'
),
array(
'username' => 'bob',
'likes' => 100.0,
'text' => 'Hello world!'
),
array(
'username' => 'bob',
'likes' => 100.0,
'text' => 'Hello world!'
),
);

$collection = $this->getCollection();
$collection->batchInsert($data);

$map = 'function() {
emit(this.username, { count: 1, likes: this.likes });
}';

$reduce = 'function(key, values) {
var result = {count: 0, likes: 0};
values.forEach(function(value) {
result.count += value.count;
result.likes += value.likes;
});
return result;
}';

$finalize = 'function (key, value) { value.test = "test"; return value; }';

$command = [
'mapreduce' => $this->getCollection()->getName(),
'map' => new \MongoCode($map),
'reduce' => new \MongoCode($reduce),
'query' => (object) [],
'out' => ['inline' => true],
'finalize' => new \MongoCode($finalize),
];

$result = $this->getDatabase()->command($command);

$expected = [
[
'_id' => 'bob',
'value' => [
'count' => 2.0,
'likes' => 200.0,
'test' => 'test',
],
],
[
'_id' => 'jones',
'value' => [
'count' => 1.0,
'likes' => 20.0,
'test' => 'test',
],
],
];

$this->assertSame(1.0, $result['ok']);
$this->assertSame($expected, $result['results']);
}

public function testFindAndModifyResultException()
{
$this->markTestSkipped('Test fails on travis-ci - skipped while investigating this');
Expand Down

0 comments on commit 489af35

Please sign in to comment.