Skip to content

Commit

Permalink
minor refactoring + CS
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Jan 19, 2024
1 parent e4f8ba3 commit d49a95a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 34 deletions.
12 changes: 5 additions & 7 deletions src/SimpleCachingIteratorAggregate.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,23 +52,21 @@ public function getIterator(): Generator

$cache = $this->iterator->getCache();

if ($key === array_key_last($cache)) {
if (array_key_last($cache) === $key) {
continue;
}

// If the cache pointer has shifted since last iteration (inner loop over the same iterator),
// it's necessary to yield extra-cached items as well

// If the cache pointer has shifted since last iteration
// (inner loop over the same iterator), it's necessary to yield
// extra-cached items as well
$yieldStarted = false;

foreach ($cache as $cacheKey => $cacheItem) {
if ($yieldStarted) {
yield $cacheKey => $cacheItem;
}

if ($key === $cacheKey) {
$yieldStarted = true;
}
$yieldStarted = $yieldStarted || $key === $cacheKey;
}
}
}
Expand Down
50 changes: 23 additions & 27 deletions tests/unit/SimpleCachingIteratorAggregateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,29 @@
*/
final class SimpleCachingIteratorAggregateTest extends TestCase
{
public function testConsecutiveCachingFromInnerTraversals(): void
{
$iterator = new SimpleCachingIteratorAggregate(new ArrayIterator([1, 2, 3, 4, 5, 6]));
$outerItems = $innerItems = [];

foreach ($iterator as $outerItem) {
$outerItems[] = $outerItem;

if (2 === $outerItem) {
foreach ($iterator as $innerItem) {
$innerItems[] = $innerItem;

if (4 === $innerItem) {
break;
}
}
}
}

self::assertSame([1, 2, 3, 4], $innerItems);
self::assertSame([1, 2, 3, 4, 5, 6], $outerItems);
}

public function testHasNext(): void
{
$range = range('a', 'c');
Expand Down Expand Up @@ -105,31 +128,4 @@ public function testWithAHalfAGenerator(): void

self::assertSame($expected, $a);
}

public function testConsecutiveCachingFromInnerTraversals(): void
{
$iterator = new SimpleCachingIteratorAggregate(new ArrayIterator([1, 2, 3, 4, 5, 6]));

$outerItems = [];

foreach ($iterator as $outerItem) {
if ($outerItem === 2) {
$innerItems = [];

foreach ($iterator as $innerItem) {
$innerItems[] = $innerItem;

if ($innerItem === 4) {
break;
}
}

self::assertSame([1, 2, 3, 4], $innerItems);
}

$outerItems[] = $outerItem;
}

self::assertSame([1, 2, 3, 4, 5, 6], $outerItems);
}
}

0 comments on commit d49a95a

Please sign in to comment.