Skip to content

Commit a9ccce6

Browse files
authored
Add count method to InMemoryRepository (#42)
There's a non-interface method (that's noted as "add to interface in next major version" internally) to get a count of a result set. This adds the same to Mocktrine.
1 parent 2b774fe commit a9ccce6

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ The following methods on Doctrine's `EntityManagerInterface` should all work as
5353
- getCache (will always return `null`)
5454
- isOpen (will always return `true`)
5555

56-
All methods on the `ObjectRepository` (for various findBy operations) should also work.
56+
All methods on the `ObjectRepository` (for various findBy operations) should also work, as well as the non-interface `count($criteria)` method.
5757
`ObjectRepository` also implements the `Selectable` interface (as `EntityRepository` does, which is the returned type from `EntityManager`), so it's also possible to use the `matching(Criteria)` method.
5858

5959
The following methods are **not** supported at this time:

src/InMemoryRepository.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,19 @@ public function findBy(array $criteria, ?array $orderBy = null, $limit = null, $
199199
return $this->doMatch($crit);
200200
}
201201

202+
/**
203+
* Counts entities by a set of critieria.
204+
*
205+
* NOTE: this is not part of the official interface; there's
206+
* a Doctrine-internal TODO to make it so.
207+
*
208+
* @param array<string, mixed> $criteria
209+
*/
210+
public function count(array $criteria): int
211+
{
212+
return count($this->findBy($criteria));
213+
}
214+
202215
/**
203216
* Finds a single object by a set of criteria.
204217
*

tests/InMemoryRepositoryTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,18 @@ public function testSimpleFindBy(): void
7474
$this->assertSame('2@example.com', $results[1]->getEmail());
7575
}
7676

77+
public function testCount(): void
78+
{
79+
$repo = $this->getFixture();
80+
self::assertSame(5, $repo->count([]));
81+
self::assertSame(2, $repo->count(['lastName' => 'last']));
82+
self::assertSame(3, $repo->count(['lastName' => 'other']));
83+
self::assertSame(1, $repo->count(['email' => '1@example.com', 'lastName' => 'last']));
84+
self::assertSame(0, $repo->count(['email' => '1@example.com', 'lastName' => 'other']));
85+
self::assertSame(1, $repo->count(['email' => '1@example.com']));
86+
self::assertSame(0, $repo->count(['email' => '6@example.com']));
87+
}
88+
7789
public function testFindByWithArrayValue(): void
7890
{
7991
$repo = $this->getFixture();

0 commit comments

Comments
 (0)