aurimasniekis/doctrine-collection-updater

Doctrine Doctrine 集合元素更新器

1.1.0 2017-10-13 14:46 UTC

This package is auto-updated.

Last update: 2024-09-14 02:53:20 UTC


README

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

Email

Doctrine Collection Updater 提供了一个特质,用于根据比较器数组(例如 id)更新集合(创建、删除)中的元素。

安装

通过 Composer

$ composer require aurimasniekis/doctrine-collection-updater

用法

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

测试

$ composer test

贡献

请参阅 CONTRIBUTINGCONDUCT 获取详细信息。

许可证

请参阅 许可证文件 获取更多信息。