]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Helper/TagsAssigner.php
Replace continue; with break; to avoid PHP 7.3 warnings
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Helper / TagsAssigner.php
CommitLineData
6bc6fb1f
TC
1<?php
2
3namespace Wallabag\CoreBundle\Helper;
4
5use Wallabag\CoreBundle\Entity\Entry;
6use Wallabag\CoreBundle\Entity\Tag;
7use Wallabag\CoreBundle\Repository\TagRepository;
8
9class TagsAssigner
10{
6bc6fb1f 11 /**
5d3deafd 12 * @var TagRepository
6bc6fb1f
TC
13 */
14 protected $tagRepository;
15
16 public function __construct(TagRepository $tagRepository)
17 {
18 $this->tagRepository = $tagRepository;
19 }
20
21 /**
22 * Assign some tags to an entry.
23 *
24 * @param Entry $entry
25 * @param array|string $tags An array of tag or a string coma separated of tag
26 * @param array $entitiesReady Entities from the EntityManager which are persisted but not yet flushed
27 * It is mostly to fix duplicate tag on import @see http://stackoverflow.com/a/7879164/569101
28 *
29 * @return Tag[]
30 */
31 public function assignTagsToEntry(Entry $entry, $tags, array $entitiesReady = [])
32 {
33 $tagsEntities = [];
34
2a1ceb67 35 if (!\is_array($tags)) {
6bc6fb1f
TC
36 $tags = explode(',', $tags);
37 }
38
39 // keeps only Tag entity from the "not yet flushed entities"
40 $tagsNotYetFlushed = [];
41 foreach ($entitiesReady as $entity) {
42 if ($entity instanceof Tag) {
43 $tagsNotYetFlushed[$entity->getLabel()] = $entity;
44 }
45 }
46
47 foreach ($tags as $label) {
7036d91f 48 $label = trim(mb_convert_case($label, MB_CASE_LOWER));
6bc6fb1f
TC
49
50 // avoid empty tag
2a1ceb67 51 if (0 === \strlen($label)) {
ceddccb7 52 break;
6bc6fb1f
TC
53 }
54
55 if (isset($tagsNotYetFlushed[$label])) {
56 $tagEntity = $tagsNotYetFlushed[$label];
57 } else {
58 $tagEntity = $this->tagRepository->findOneByLabel($label);
59
60 if (null === $tagEntity) {
61 $tagEntity = new Tag();
62 $tagEntity->setLabel($label);
63 }
64 }
65
66 // only add the tag on the entry if the relation doesn't exist
67 if (false === $entry->getTags()->contains($tagEntity)) {
68 $entry->addTag($tagEntity);
69 $tagsEntities[] = $tagEntity;
70 }
71 }
72
73 return $tagsEntities;
74 }
75}