3 namespace Wallabag\CoreBundle\Helper
;
5 use Wallabag\CoreBundle\Entity\Entry
;
6 use Wallabag\CoreBundle\Entity\Tag
;
7 use Wallabag\CoreBundle\Repository\TagRepository
;
13 * @var TagRepository $tagRepository
15 protected $tagRepository;
17 public function __construct(TagRepository
$tagRepository)
19 $this->tagRepository
= $tagRepository;
23 * Assign some tags to an entry.
26 * @param array|string $tags An array of tag or a string coma separated of tag
27 * @param array $entitiesReady Entities from the EntityManager which are persisted but not yet flushed
28 * It is mostly to fix duplicate tag on import @see http://stackoverflow.com/a/7879164/569101
32 public function assignTagsToEntry(Entry
$entry, $tags, array $entitiesReady = [])
36 if (!is_array($tags)) {
37 $tags = explode(',', $tags);
40 // keeps only Tag entity from the "not yet flushed entities"
41 $tagsNotYetFlushed = [];
42 foreach ($entitiesReady as $entity) {
43 if ($entity instanceof Tag
) {
44 $tagsNotYetFlushed[$entity->getLabel()] = $entity;
48 foreach ($tags as $label) {
49 $label = trim($label);
52 if (0 === strlen($label)) {
56 if (isset($tagsNotYetFlushed[$label])) {
57 $tagEntity = $tagsNotYetFlushed[$label];
59 $tagEntity = $this->tagRepository
->findOneByLabel($label);
61 if (null === $tagEntity) {
62 $tagEntity = new Tag();
63 $tagEntity->setLabel($label);
67 // only add the tag on the entry if the relation doesn't exist
68 if (false === $entry->getTags()->contains($tagEntity)) {
69 $entry->addTag($tagEntity);
70 $tagsEntities[] = $tagEntity;