https://g.co/gemini/share/163c471db588
// src/Entity/BookCollection.php
namespace App\Entity;
use App\Entity\Book;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
#[ORM\Entity]
#[Assert\Traverse]
class BookCollection implements \IteratorAggregate
{
/**
* @var string
*/
#[ORM\Column]
#[Assert\NotBlank]
protected string $name = '';
/**
* @var Collection|Book[]
*/
#[ORM\ManyToMany(targetEntity: Book::class)]
protected ArrayCollection $books;
// some other properties
public function __construct()
{
$this->books = new ArrayCollection();
}
// ... setter for name, adder and remover for books
// the name can be validated by calling the getter
public function getName(): string
{
return $this->name;
}
/**
* @return \Generator|Book[] The books for a given author
*/
public function getBooksForAuthor(Author $author): iterable
{
foreach ($this->books as $book) {
if ($book->isAuthoredBy($author)) {
yield $book;
}
}
}
// neither the method above nor any other specific getter
// could be used to validated all nested books;
// this object needs to be traversed to call the iterator
public function getIterator(): \Iterator
{
return $this->books->getIterator();
}
}Powered by Froala Editor