mirror of
https://github.com/DesignPatternsPHP/DesignPatternsPHP.git
synced 2025-06-01 19:45:13 +02:00
62 lines
1.1 KiB
PHP
62 lines
1.1 KiB
PHP
<?php declare(strict_types=1);
|
|
|
|
namespace DesignPatterns\Behavioral\Iterator;
|
|
|
|
use Countable;
|
|
use Iterator;
|
|
|
|
class BookList implements Countable, Iterator
|
|
{
|
|
/**
|
|
* @var Book[]
|
|
*/
|
|
private array $books = [];
|
|
private int $currentIndex = 0;
|
|
|
|
public function addBook(Book $book)
|
|
{
|
|
$this->books[] = $book;
|
|
}
|
|
|
|
public function removeBook(Book $bookToRemove)
|
|
{
|
|
foreach ($this->books as $key => $book) {
|
|
if ($book->getAuthorAndTitle() === $bookToRemove->getAuthorAndTitle()) {
|
|
unset($this->books[$key]);
|
|
}
|
|
}
|
|
|
|
$this->books = array_values($this->books);
|
|
}
|
|
|
|
public function count(): int
|
|
{
|
|
return count($this->books);
|
|
}
|
|
|
|
public function current(): Book
|
|
{
|
|
return $this->books[$this->currentIndex];
|
|
}
|
|
|
|
public function key(): int
|
|
{
|
|
return $this->currentIndex;
|
|
}
|
|
|
|
public function next()
|
|
{
|
|
$this->currentIndex++;
|
|
}
|
|
|
|
public function rewind()
|
|
{
|
|
$this->currentIndex = 0;
|
|
}
|
|
|
|
public function valid(): bool
|
|
{
|
|
return isset($this->books[$this->currentIndex]);
|
|
}
|
|
}
|