Fixed query to count tags when a search term is present

This commit is contained in:
Alejandro Celaya 2022-01-06 12:22:05 +01:00
parent ead8cc6cec
commit d00a56bec0
2 changed files with 29 additions and 17 deletions

View file

@ -23,11 +23,18 @@ abstract class AbstractTagsPaginatorAdapter implements AdapterInterface
public function getNbResults(): int
{
return (int) $this->repo->matchSingleScalarResult(Spec::andX(
// FIXME I don't think using Spec::selectNew is the correct thing here, ideally it should be Spec::select,
// but seems to be the only way to use Spec::COUNT(...)
$conditions = [
// FIXME I don't think using Spec::selectNew is the correct thing in this context.
// Ideally it should be Spec::select, but seems to be the only way to use Spec::COUNT(...).
Spec::selectNew(Tag::class, Spec::COUNT('id', true)),
new WithApiKeySpecsEnsuringJoin($this->apiKey),
));
];
$searchTerm = $this->params->searchTerm();
if ($searchTerm !== null) {
$conditions[] = Spec::like('name', $searchTerm);
}
return (int) $this->repo->matchSingleScalarResult(Spec::andX(...$conditions));
}
}

View file

@ -23,8 +23,13 @@ class TagsPaginatorAdapterTest extends DatabaseTestCase
* @test
* @dataProvider provideFilters
*/
public function expectedListOfTagsIsReturned(?string $searchTerm, int $offset, int $length, int $expected): void
{
public function expectedListOfTagsIsReturned(
?string $searchTerm,
int $offset,
int $length,
int $expectedSliceSize,
int $expectedTotalCount,
): void {
$names = ['foo', 'bar', 'baz', 'another'];
foreach ($names as $name) {
$this->getEntityManager()->persist(new Tag($name));
@ -33,20 +38,20 @@ class TagsPaginatorAdapterTest extends DatabaseTestCase
$adapter = new TagsPaginatorAdapter($this->repo, TagsParams::fromRawData(['searchTerm' => $searchTerm]), null);
self::assertCount($expected, $adapter->getSlice($offset, $length));
self::assertEquals(4, $adapter->getNbResults());
self::assertCount($expectedSliceSize, $adapter->getSlice($offset, $length));
self::assertEquals($expectedTotalCount, $adapter->getNbResults());
}
public function provideFilters(): iterable
{
yield [null, 0, 10, 4];
yield [null, 2, 10, 2];
yield [null, 1, 3, 3];
yield [null, 3, 3, 1];
yield [null, 0, 2, 2];
yield ['ba', 0, 10, 2];
yield ['ba', 0, 1, 1];
yield ['foo', 0, 10, 1];
yield ['a', 0, 10, 3];
yield [null, 0, 10, 4, 4];
yield [null, 2, 10, 2, 4];
yield [null, 1, 3, 3, 4];
yield [null, 3, 3, 1, 4];
yield [null, 0, 2, 2, 4];
yield ['ba', 0, 10, 2, 2];
yield ['ba', 0, 1, 1, 2];
yield ['foo', 0, 10, 1, 1];
yield ['a', 0, 10, 3, 3];
}
}