Doctrine Collection Updater
, (*1)
, (*2)
Doctrine Collection Updater provides a trait to update collection (create, remove) element from collection based on array of comparators for e.g. id., (*3)
Install
Via Composer, (*4)
$ composer require aurimasniekis/doctrine-collection-updater
Usage
<?php
use AurimasNiekis\DoctrineCollectionUpdater\CollectionUpdaterTrait;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\EntityRepository;
class Tag
{
/**
* @var int
*/
private $id;
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @param int $id
*
* @return Tag
*/
public function setId(int $id): Tag
{
$this->id = $id;
return $this;
}
}
class Item
{
/**
* @var int[]
*/
private $rawTags;
/**
* @var Tag[]|Collection
*/
private $tags;
public function __construct()
{
$this->tags = new ArrayCollection();
}
/**
* @return int[]
*/
public function getRawTags(): array
{
return $this->rawTags;
}
/**
* @param int[] $rawTags
*
* @return Item
*/
public function setRawTags(array $rawTags): Item
{
$this->rawTags = $rawTags;
return $this;
}
/**
* @return Collection|Tag[]
*/
public function getTags(): Collection
{
return $this->tags;
}
/**
* @param Collection|Tag[] $tags
*
* @return Item
*/
public function setTags($tags)
{
$this->tags = $tags;
return $this;
}
}
class ItemRepository extends EntityRepository
{
use CollectionUpdaterTrait;
public function save(Item $item)
{
$em = $this->getEntityManager();
$tags = $this->updateCollection(
$item->getTags(),
$item->getRawTags(),
function (Item $item): int {
return $item->getId();
},
function (int $id) use ($em): Item {
$tag = new Tag();
$tag->setId($id);
$em->persist($tag);
return $tag;
}
);
$item->setTags($tags);
$em->persist($item);
$em->flush();
}
}
Testing
$ composer test
Contributing
Please see CONTRIBUTING and CONDUCT for details., (*5)
License
Please see License File for more information., (*6)