Skip to content

Commit 7484b73

Browse files
authored
fix(BulkLoader): Handle empty entity collection without throwing exception (#543)
1 parent 38360e9 commit 7484b73

File tree

3 files changed

+18
-8
lines changed

3 files changed

+18
-8
lines changed

src/Relation/BulkLoader.php

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,16 @@ public function __construct(
2929

3030
public function collect(object ...$entities): RelationLoaderInterface
3131
{
32-
$entities === [] and throw new \InvalidArgumentException('At least one entity must be provided.');
32+
if ($entities === []) {
33+
return new class implements RelationLoaderInterface {
34+
public function load(string $relation, array $options = []): static
35+
{
36+
return $this;
37+
}
38+
39+
public function run(): void {}
40+
};
41+
}
3342
$entities = \array_values($entities);
3443

3544
// Validate entity roles
@@ -112,7 +121,7 @@ public function run(): void
112121
* @param non-empty-array<non-empty-string> $keys
113122
* @param non-empty-array<non-empty-string> $data
114123
*/
115-
public function indexEntity(Node $node, array $keys, array $data, object $entity): void
124+
private function indexEntity(Node $node, array $keys, array $data, object $entity): void
116125
{
117126
$pool = &$this->index;
118127
foreach ($keys as $k) {

src/Relation/BulkLoaderInterface.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ interface BulkLoaderInterface
1212
/**
1313
* Collect entities for bulk relation loading.
1414
*
15+
* If no entities are provided, a no-op loader is returned.
16+
*
1517
* @param object ...$entities Entities to collect
1618
* @psalm-immutable
1719
*/

tests/ORM/Unit/Relation/BulkLoaderTest.php

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use Cycle\ORM\Mapper\Mapper;
99
use Cycle\ORM\ORM;
1010
use Cycle\ORM\Relation\BulkLoader;
11+
use Cycle\ORM\Relation\RelationLoaderInterface;
1112
use Cycle\ORM\Schema;
1213
use Cycle\ORM\Tests\Fixtures\User;
1314
use Cycle\ORM\Tests\Fixtures\Profile;
@@ -130,14 +131,12 @@ public function testChainingMultipleCollectCalls(): void
130131
*/
131132
public function testCollectWithEmptyArrayUnpacking(): void
132133
{
133-
$this->expectException(\InvalidArgumentException::class);
134-
$this->expectExceptionMessage('At least one entity must be provided.');
135-
136134
$orm = $this->createORM();
137-
$entities = [];
135+
$loader = (new BulkLoader($orm))->collect();
138136

139-
$loader = new BulkLoader($orm);
140-
$loader->collect(...$entities);
137+
self::assertInstanceOf(RelationLoaderInterface::class, $loader);
138+
$loader->load('profile');
139+
$loader->run();
141140
}
142141

143142
/**

0 commit comments

Comments
 (0)