Skip to content

Commit 923616b

Browse files
Merge pull request #42 from jrattue/master
Add support for distinct
2 parents fe8bbee + 6f43140 commit 923616b

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/MockCollection.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -385,7 +385,15 @@ public function deleteOne($filter, array $options = [])
385385

386386
public function distinct($fieldName, $filter = [], array $options = [])
387387
{
388-
// TODO: Implement this function
388+
$values = [];
389+
390+
$matcher = $this->matcherFromQuery($filter);
391+
foreach ($this->documents as $document){
392+
if ($matcher($document) && isset($document[$fieldName])) {
393+
$values[] = $document[$fieldName];
394+
}
395+
}
396+
return array_unique($values);
389397
}
390398

391399
public function dropIndex($indexName, array $options = [])

tests/MockCollectionTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1162,4 +1162,22 @@ public function testFindScalarValueInArray()
11621162
self::assertInstanceOf(BSONDocument::class, $document);
11631163
self::assertArrayHasKey('foo', $document);
11641164
}
1165+
1166+
/**
1167+
* @depends testInsertManyInsertsDocuments
1168+
*/
1169+
public function testDistinct()
1170+
{
1171+
$this->col->insertMany([
1172+
['foo' => 'foo', 'bar' => 1],
1173+
['foo' => 'bar', 'bar' => 1],
1174+
['foo' => 'baz', 'bar' => 2],
1175+
]);
1176+
1177+
self::assertThat($this->col->distinct('foo'), self::equalTo(['foo', 'bar', 'baz']));
1178+
self::assertThat($this->col->distinct('missing'), self::equalTo([]));
1179+
self::assertThat($this->col->distinct('foo', ['bar' => 1]), self::equalTo(['foo', 'bar']));
1180+
self::assertThat($this->col->distinct('foo', ['bar' => 2]), self::equalTo(['baz']));
1181+
}
1182+
11651183
}

0 commit comments

Comments
 (0)