aurimasniekis/doctrine-collection-updater

Doctrine Doctrine collection element updater

1.1.0 2017-10-13 14:46 UTC

This package is auto-updated.

Last update: 2024-12-14 03:18:47 UTC


README

Latest Version Software License Build Status Code Coverage Quality Score Total Downloads

Email

Doctrine Collection Updater provides a trait to update collection (create, remove) element from collection based on array of comparators for e.g. id.

Install

Via Composer

$ 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.

License

Please see License File for more information.