<?php
class BeforeAfterIterator implements Iterator
{
private $iterator;
public function __construct(iterable $iterator, $before, $after)
{
if (!$iterator instanceof Iterator) {
$iterator = (function ($iterable) {
yield from $iterable;
})($iterator);
}
if ($iterator->valid()) {
$this->iterator = new AppendIterator();
$this->iterator->append(new ArrayIterator([$before]));
$this->iterator->append($iterator);
$this->iterator->append(new ArrayIterator([$after]));
} else {
$this->iterator = new ArrayIterator([]);
}
}
public function current()
{
return $this->iterator->current();
}
public function next()
{
$this->iterator->next();
}
public function key()
{
return $this->iterator->key();
}
public function valid()
{
return $this->iterator->valid();
}
public function rewind()
{
$this->iterator->rewind();
}
}
$begin = new DateTime('2020-02-01');
$end = new DateTime('2020-02-29');
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);
foreach (new BeforeAfterIterator($daterange, new \DateTime('2020-01-31'), new \DateTime('2020-03-01')) as $value) {
echo $value->format('Y-m-d'), PHP_EOL;
}
foreach (new BeforeAfterIterator(range(1, 10), 'Before', 'After') as $value) {
echo $value, PHP_EOL;
}
function generator() {
yield from [1, 2, 3, 4, 5];
}
foreach (new BeforeAfterIterator(generator(), 'Before', 'After') as $value) {
echo $value, PHP_EOL;
}
Deprecated: Return type of BeforeAfterIterator::current() should either be compatible with Iterator::current(): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /in/0Xa1a on line 24
Deprecated: Return type of BeforeAfterIterator::next() should either be compatible with Iterator::next(): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /in/0Xa1a on line 29
Deprecated: Return type of BeforeAfterIterator::key() should either be compatible with Iterator::key(): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /in/0Xa1a on line 34
Deprecated: Return type of BeforeAfterIterator::valid() should either be compatible with Iterator::valid(): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /in/0Xa1a on line 39
Deprecated: Return type of BeforeAfterIterator::rewind() should either be compatible with Iterator::rewind(): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /in/0Xa1a on line 44
2020-01-31
2020-02-01
2020-02-02
2020-02-03
2020-02-04
2020-02-05
2020-02-06
2020-02-07
2020-02-08
2020-02-09
2020-02-10
2020-02-11
2020-02-12
2020-02-13
2020-02-14
2020-02-15
2020-02-16
2020-02-17
2020-02-18
2020-02-19
2020-02-20
2020-02-21
2020-02-22
2020-02-23
2020-02-24
2020-02-25
2020-02-26
2020-02-27
2020-02-28
2020-03-01
Before
1
2
3
4
5
6
7
8
9
10
After
Before
1
2
3
4
5
After