PHP code example of aurimasniekis / doctrine-collection-updater

1. Go to this page and download the library: Download aurimasniekis/doctrine-collection-updater library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

aurimasniekis / doctrine-collection-updater example snippets




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();
    }
}