Skip to content

Commit e82cda0

Browse files
authored
Add helper to ease creating an empty result (#497)
Creating an empty search result is a very valid case and because creating an empty generator is a bit cumbersome, I think this qualifies for a helper factory method 😊
1 parent 50bf798 commit e82cda0

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

packages/seal/src/Search/Result.php

+8-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
/**
1717
* @extends \IteratorIterator<int, array<string, mixed>, \Generator>
1818
*/
19-
class Result extends \IteratorIterator
19+
final class Result extends \IteratorIterator
2020
{
2121
/**
2222
* @param \Generator<int, array<string, mixed>> $documents
@@ -32,4 +32,11 @@ public function total(): int
3232
{
3333
return $this->total;
3434
}
35+
36+
public static function createEmpty(): static
37+
{
38+
return new self((static function (): \Generator {
39+
yield from [];
40+
})(), 0);
41+
}
3542
}
+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/*
6+
* This file is part of the CMS-IG SEAL project.
7+
*
8+
* (c) Alexander Schranz <[email protected]>
9+
*
10+
* For the full copyright and license information, please view the LICENSE
11+
* file that was distributed with this source code.
12+
*/
13+
14+
namespace CmsIg\Seal\Tests\Search;
15+
16+
use CmsIg\Seal\Search\Result;
17+
use PHPUnit\Framework\TestCase;
18+
19+
class ResultTest extends TestCase
20+
{
21+
public function testIteratingResult(): void
22+
{
23+
$result = new Result((static function (): \Generator {
24+
yield ['id' => 42];
25+
})(), 1);
26+
27+
$this->assertSame(1, $result->total());
28+
$this->assertSame([['id' => 42]], \iterator_to_array($result));
29+
}
30+
31+
public function testCreateEmptyResult(): void
32+
{
33+
$result = Result::createEmpty();
34+
$this->assertSame(0, $result->total());
35+
$this->assertSame([], \iterator_to_array($result));
36+
}
37+
}

0 commit comments

Comments
 (0)