]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Helper/RuleBasedTagger.php
Merge pull request #1915 from wallabag/doc-links
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Helper / RuleBasedTagger.php
CommitLineData
c3510620
KG
1<?php
2
3namespace Wallabag\CoreBundle\Helper;
4
5use RulerZ\RulerZ;
c3510620
KG
6use Wallabag\CoreBundle\Entity\Entry;
7use Wallabag\CoreBundle\Entity\Tag;
625acf33 8use Wallabag\CoreBundle\Repository\EntryRepository;
c3510620
KG
9use Wallabag\CoreBundle\Repository\TagRepository;
10use Wallabag\UserBundle\Entity\User;
11
12class RuleBasedTagger
13{
14 private $rulerz;
15 private $tagRepository;
625acf33 16 private $entryRepository;
c3510620 17
625acf33 18 public function __construct(RulerZ $rulerz, TagRepository $tagRepository, EntryRepository $entryRepository)
c3510620 19 {
347fa6be
NL
20 $this->rulerz = $rulerz;
21 $this->tagRepository = $tagRepository;
625acf33 22 $this->entryRepository = $entryRepository;
c3510620
KG
23 }
24
25 /**
26 * Add tags from rules defined by the user.
27 *
28 * @param Entry $entry Entry to tag.
29 */
30 public function tag(Entry $entry)
31 {
32 $rules = $this->getRulesForUser($entry->getUser());
33
34 foreach ($rules as $rule) {
ac9fec61 35 if (!$this->rulerz->satisfies($entry, $rule->getRule())) {
c3510620
KG
36 continue;
37 }
38
ac9fec61 39 foreach ($rule->getTags() as $label) {
fc732227 40 $tag = $this->getTag($label);
c3510620
KG
41
42 $entry->addTag($tag);
43 }
44 }
45 }
46
625acf33
KG
47 /**
48 * Apply all the tagging rules defined by a user on its entries.
49 *
50 * @param User $user
51 *
52 * @return array<Entry> A list of modified entries.
53 */
54 public function tagAllForUser(User $user)
55 {
347fa6be 56 $rules = $this->getRulesForUser($user);
625acf33
KG
57 $entries = array();
58
59 foreach ($rules as $rule) {
347fa6be 60 $qb = $this->entryRepository->getBuilderForAllByUser($user->getId());
625acf33
KG
61 $entries = $this->rulerz->filter($qb, $rule->getRule());
62
63 foreach ($entries as $entry) {
64 foreach ($rule->getTags() as $label) {
fc732227 65 $tag = $this->getTag($label);
625acf33
KG
66
67 $entry->addTag($tag);
625acf33
KG
68 }
69 }
70 }
71
72 return $entries;
73 }
74
c3510620 75 /**
fc732227 76 * Fetch a tag.
c3510620 77 *
c3510620
KG
78 * @param string $label The tag's label.
79 *
80 * @return Tag
81 */
fc732227 82 private function getTag($label)
c3510620 83 {
fc732227 84 $tag = $this->tagRepository->findOneByLabel($label);
c3510620
KG
85
86 if (!$tag) {
fc732227 87 $tag = new Tag();
c3510620
KG
88 $tag->setLabel($label);
89 }
90
91 return $tag;
92 }
93
ac9fec61
KG
94 /**
95 * Retrieves the tagging rules for a given user.
96 *
97 * @param User $user
98 *
99 * @return array<TaggingRule>
100 */
c3510620
KG
101 private function getRulesForUser(User $user)
102 {
ac9fec61 103 return $user->getConfig()->getTaggingRules();
c3510620
KG
104 }
105}