]>
Commit | Line | Data |
---|---|---|
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 | { | |
11 | /** | |
12 | * @var TagRepository | |
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 | ||
35 | if (!is_array($tags)) { | |
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) { | |
48 | $label = trim($label); | |
49 | ||
50 | // avoid empty tag | |
51 | if (0 === strlen($label)) { | |
52 | continue; | |
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 | } |