Skip to content

Commit

Permalink
Add count method to InMemoryRepository (#42)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Firehed authored Jan 30, 2024
1 parent 2b774fe commit a9ccce6
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ The following methods on Doctrine's `EntityManagerInterface` should all work as
- getCache (will always return `null`)
- isOpen (will always return `true`)

All methods on the `ObjectRepository` (for various findBy operations) should also work.
All methods on the `ObjectRepository` (for various findBy operations) should also work, as well as the non-interface `count($criteria)` method.
`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.

The following methods are **not** supported at this time:
Expand Down
13 changes: 13 additions & 0 deletions src/InMemoryRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,19 @@ public function findBy(array $criteria, ?array $orderBy = null, $limit = null, $
return $this->doMatch($crit);
}

/**
* Counts entities by a set of critieria.
*
* NOTE: this is not part of the official interface; there's
* a Doctrine-internal TODO to make it so.
*
* @param array<string, mixed> $criteria
*/
public function count(array $criteria): int
{
return count($this->findBy($criteria));
}

/**
* Finds a single object by a set of criteria.
*
Expand Down
12 changes: 12 additions & 0 deletions tests/InMemoryRepositoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,18 @@ public function testSimpleFindBy(): void
$this->assertSame('[email protected]', $results[1]->getEmail());
}

public function testCount(): void
{
$repo = $this->getFixture();
self::assertSame(5, $repo->count([]));
self::assertSame(2, $repo->count(['lastName' => 'last']));
self::assertSame(3, $repo->count(['lastName' => 'other']));
self::assertSame(1, $repo->count(['email' => '[email protected]', 'lastName' => 'last']));
self::assertSame(0, $repo->count(['email' => '[email protected]', 'lastName' => 'other']));
self::assertSame(1, $repo->count(['email' => '[email protected]']));
self::assertSame(0, $repo->count(['email' => '[email protected]']));
}

public function testFindByWithArrayValue(): void
{
$repo = $this->getFixture();
Expand Down

0 comments on commit a9ccce6

Please sign in to comment.