<?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;
}