Skip to content

Instantly share code, notes, and snippets.

@devster
Last active November 2, 2019 12:49
Show Gist options
  • Save devster/a16bb84a297672b7b3f36fe73e07323a to your computer and use it in GitHub Desktop.
Save devster/a16bb84a297672b7b3f36fe73e07323a to your computer and use it in GitHub Desktop.
Heterogene iterable queue concept
<?php
namespace App\Core\Pipeline;
class Queue
{
/**
* @var \AppendIterator
*/
private $iterator;
public function __construct()
{
$this->reset();
}
public function append($items): void
{
$items = is_iterable($items) ? $items : [$items];
$items = is_array($items) ? new \ArrayIterator($items) : $items;
$this->iterator->append($items);
}
public function next()
{
$item = $this->iterator->current();
$this->iterator->next();
return $item;
}
public function reset(): void
{
$this->iterator = new \AppendIterator();
}
public function hasNext(): bool
{
return $this->iterator->valid();
}
}
<?php
declare(strict_types=1);
namespace App\Tests\Core\Pipeline;
use App\Core\Pipeline\Queue;
use PHPUnit\Framework\TestCase;
class QueueTest extends TestCase
{
public function testQueue()
{
$items = [1, 2];
$itemGenerator = function() {
yield 5;
yield 6;
};
$queue = new Queue();
$this->assertFalse($queue->hasNext());
$queue->append($items);
$queue->append(3);
$this->assertTrue($queue->hasNext());
$this->assertSame(1, $queue->next());
$this->assertTrue($queue->hasNext());
$this->assertSame(2, $queue->next());
$this->assertTrue($queue->hasNext());
$this->assertSame(3, $queue->next());
$this->assertFalse($queue->hasNext());
$this->assertNull($queue->next());
$queue->append($itemGenerator());
$this->assertTrue($queue->hasNext());
$this->assertSame(5, $queue->next());
$this->assertTrue($queue->hasNext());
$this->assertSame(6, $queue->next());
$this->assertFalse($queue->hasNext());
$queue->append([]);
$this->assertFalse($queue->hasNext());
}
public function testReset()
{
$items = [1, 2];
$queue = new Queue();
$queue->append($items);
$this->assertTrue($queue->hasNext());
$this->assertSame(1, $queue->next());
$this->assertTrue($queue->hasNext());
$queue->reset();
$this->assertFalse($queue->hasNext());
$this->assertNull($queue->next());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment