1
0
mirror of https://github.com/php/php-src.git synced 2026-04-04 22:52:40 +02:00
Files
archived-php-src/ext/date/tests/DatePeriod_IteratorAggregate.phpt
Nikita Popov ff19ec2df3 Introduce InternalIterator
Userland classes that implement Traversable must do so either
through Iterator or IteratorAggregate. The same requirement does
not exist for internal classes: They can implement the internal
get_iterator mechanism, without exposing either the Iterator or
IteratorAggregate APIs. This makes them usable in get_iterator(),
but incompatible with any Iterator based APIs.

A lot of internal classes do this, because exposing the userland
APIs is simply a lot of work. This patch alleviates this issue by
providing a generic InternalIterator class, which acts as an
adapater between get_iterator and Iterator, and can be easily
used by many internal classes. At the same time, we extend the
requirement that Traversable implies Iterator or IteratorAggregate
to internal classes as well.

Closes GH-5216.
2020-06-24 15:31:41 +02:00

89 lines
1.6 KiB
PHP

--TEST--
DatePeriod can be used as an IteratorAggregate
--FILE--
<?php
$period = new DatePeriod('R2/2012-07-01T00:00:00Z/P7D');
foreach ($period as $i => $date) {
echo "$i: ", $date->format('Y-m-d'), "\n";
}
echo "\n";
foreach ($period->getIterator() as $i => $date) {
echo "$i: ", $date->format('Y-m-d'), "\n";
}
echo "\n";
$iter = $period->getIterator();
for (; $iter->valid(); $iter->next()) {
$i = $iter->key();
$date = $iter->current();
echo "$i: ", $date->format('Y-m-d'), "\n";
}
echo "\n";
$iter->rewind();
for (; $iter->valid(); $iter->next()) {
$i = $iter->key();
$date = $iter->current();
echo "$i: ", $date->format('Y-m-d'), "\n";
}
echo "\n";
foreach (new IteratorIterator($period) as $i => $date) {
echo "$i: ", $date->format('Y-m-d'), "\n";
}
// Extension that does not overwrite getIterator().
class MyDatePeriod1 extends DatePeriod {
}
echo "\n";
$period = new MyDatePeriod1('R2/2012-07-01T00:00:00Z/P7D');
foreach ($period as $i => $date) {
echo "$i: ", $date->format('Y-m-d'), "\n";
}
// Extension that does overwrite getIterator().
class MyDatePeriod2 extends DatePeriod {
public function getIterator(): Iterator {
return new ArrayIterator([1, 2, 3]);
}
}
echo "\n";
$period = new MyDatePeriod2('R2/2012-07-01T00:00:00Z/P7D');
foreach ($period as $i => $notDate) {
echo "$i: $notDate\n";
}
?>
--EXPECT--
0: 2012-07-01
1: 2012-07-08
2: 2012-07-15
0: 2012-07-01
1: 2012-07-08
2: 2012-07-15
0: 2012-07-01
1: 2012-07-08
2: 2012-07-15
0: 2012-07-01
1: 2012-07-08
2: 2012-07-15
0: 2012-07-01
1: 2012-07-08
2: 2012-07-15
0: 2012-07-01
1: 2012-07-08
2: 2012-07-15
0: 1
1: 2
2: 3