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