Skip to content

Commit

Permalink
Add batch size as parameter to selectBatch
Browse files Browse the repository at this point in the history
This allows for arbitrary batch sizes
  • Loading branch information
justim committed May 15, 2020
1 parent 56282f4 commit 749caed
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 5 deletions.
8 changes: 5 additions & 3 deletions src/Batch.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,17 @@
*/
class Batch extends Collection
{
private const MAX_BATCH_SIZE = 100;
private const DEFAULT_BATCH_SIZE = 100;

/**
* Is this batch full?
*
* @param int|null $batchSize Size of the batches
* @return bool
*/
public function isFull(): bool
public function isFull(?int $batchSize = null): bool
{
return count($this) === self::MAX_BATCH_SIZE;
$batchSize ??= self::DEFAULT_BATCH_SIZE;
return count($this) >= $batchSize;
}
}
5 changes: 3 additions & 2 deletions src/Repository.php
Original file line number Diff line number Diff line change
Expand Up @@ -219,8 +219,9 @@ public function selectOne(Query\Select $query): ?Entity
* Execute a select query in a batched fashion
*
* @param Query\Select $query Select query to be executed
* @param int|null $batchSize Size of the batches
*/
public function selectBatched(Query\Select $query): \Generator
public function selectBatched(Query\Select $query, int $batchSize = null): \Generator
{
$batch = new Batch($this->db);

Expand All @@ -229,7 +230,7 @@ public function selectBatched(Query\Select $query): \Generator
foreach ($result as $entity) {
$batch->addEntity($entity);

if ($batch->isFull()) {
if ($batch->isFull($batchSize)) {
yield $batch;

$batch = new Batch($this->db);
Expand Down
7 changes: 7 additions & 0 deletions tests/Fixtures/Repository/ProjectRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,11 @@ public function findTotalCount(): int
'int',
);
}

public function findBatchedAll(): \Generator
{
$query = new Select(Project::class, 'p');

return $this->selectBatched($query, 1);
}
}
28 changes: 28 additions & 0 deletions tests/RepositoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,32 @@ public function testSelectVirtualField(): void
$total,
);
}

/**
* @depends testInsert
*/
public function testSelectdBatched(): void
{
/** @var ProjectRepository $projectRepo */
$projectRepo = self::$db->getRepository(Project::class);

$batches = $projectRepo->findBatchedAll();

$countBatches = 0;
$countEntities = 0;
foreach ($batches as $batch) {
$this->assertEquals(1, count($batch));

foreach ($batch as $project) {
$this->assertTrue($project->hasId());

$countEntities++;
}

$countBatches++;
}

$this->assertEquals(2, $countBatches);
$this->assertEquals(2, $countEntities);
}
}

0 comments on commit 749caed

Please sign in to comment.