Skip to content

Commit

Permalink
Rewrote AggregateCurrencies to use a rewindable AppendIterator in…
Browse files Browse the repository at this point in the history
…stead of a generator

Ref: #634 (comment)
  • Loading branch information
Ocramius committed Apr 23, 2021
1 parent 756649c commit 8e0630f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
10 changes: 7 additions & 3 deletions src/Currencies/AggregateCurrencies.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Money\Currencies;

use AppendIterator;
use Money\Currencies;
use Money\Currency;
use Money\Exception\UnknownCurrencyException;
Expand Down Expand Up @@ -50,10 +51,13 @@ public function subunitFor(Currency $currency): int
/** {@inheritDoc} */
public function getIterator(): Traversable
{
/** @psalm-var AppendIterator&Traversable<int|string, Currency> $iterator */
$iterator = new AppendIterator();

foreach ($this->currencies as $currencies) {
foreach ($currencies as $currency) {
yield $currency;
}
$iterator->append($currencies->getIterator());
}

return $iterator;
}
}
31 changes: 30 additions & 1 deletion tests/Currencies/AggregateCurrenciesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,36 @@ public function it_is_iterable(): void
new Currency('EUR'),
new Currency('USD'),
],
iterator_to_array(new AggregateCurrencies([$currencies, $otherCurrencies]))
iterator_to_array(new AggregateCurrencies([$currencies, $otherCurrencies]), false)
);
}

/** @test */
public function it_can_operate_be_rewinded_and_reused(): void
{
$currencies = $this->createMock(Currencies::class);
$otherCurrencies = $this->createMock(Currencies::class);

$currencies->method('getIterator')
->willReturn(new ArrayIterator([new Currency('EUR')]));
$otherCurrencies->method('getIterator')
->willReturn(new ArrayIterator([new Currency('USD')]));

$expectedCurrencies = [
new Currency('EUR'),
new Currency('USD'),
];
$iterator = (new AggregateCurrencies([$currencies, $otherCurrencies]))
->getIterator();

self::assertEquals(
$expectedCurrencies,
iterator_to_array($iterator, false)
);
self::assertEquals(
$expectedCurrencies,
iterator_to_array($iterator, false),
'Can re-use the previous iteration'
);
}
}

0 comments on commit 8e0630f

Please sign in to comment.