Skip to content

Commit ffbe7f2

Browse files
committed
Prevent getting items from invalid iterators
The library should not stringify an iterator when it is in an invalid state because the iterator could throw an exception because of that. Signed-off-by: Henrique Moody <[email protected]>
1 parent 70c3fc4 commit ffbe7f2

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

src/Stringifiers/IteratorObjectStringifier.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,10 @@ public function stringify(mixed $raw, int $depth): ?string
3131
return null;
3232
}
3333

34+
if (!$raw->valid()) {
35+
return null;
36+
}
37+
3438
return $this->quoter->quote(
3539
$this->format($raw, 'current() =>', $this->stringifier->stringify($raw->current(), $depth + 1)),
3640
$depth

tests/unit/Stringifiers/IteratorObjectStringifierTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
namespace Respect\Stringifier\Test\Unit\Stringifiers;
1212

13+
use ArrayIterator;
1314
use ConcreteIterator;
1415
use PHPUnit\Framework\Attributes\CoversClass;
1516
use PHPUnit\Framework\Attributes\Test;
@@ -35,6 +36,14 @@ public function itShouldNotStringifyRawValueWhenItIsNotTraversable(): void
3536
self::assertNull($sut->stringify([1, 2, 3, 4], self::DEPTH));
3637
}
3738

39+
#[Test]
40+
public function itShouldNotStringifyRawValueWhenItIsIterableThatIsNotValid(): void
41+
{
42+
$sut = new IteratorObjectStringifier(new FakeStringifier(), new FakeQuoter());
43+
44+
self::assertNull($sut->stringify(new ArrayIterator([]), self::DEPTH));
45+
}
46+
3847
#[Test]
3948
public function itShouldStringifyRawValueWhenItIsAnInstanceOfIterator(): void
4049
{

0 commit comments

Comments
 (0)