3 namespace Wallabag\CoreBundle\Twig
;
5 use Doctrine\ORM\Query
;
6 use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface
;
7 use Wallabag\CoreBundle\Repository\EntryRepository
;
8 use Wallabag\CoreBundle\Repository\TagRepository
;
10 class WallabagExtension
extends \Twig_Extension
implements \Twig_Extension_GlobalsInterface
12 private $tokenStorage;
13 private $entryRepository;
14 private $tagRepository;
17 public function __construct(EntryRepository
$entryRepository = null, TagRepository
$tagRepository = null, TokenStorageInterface
$tokenStorage = null, $lifeTime = 0)
19 $this->entryRepository
= $entryRepository;
20 $this->tagRepository
= $tagRepository;
21 $this->tokenStorage
= $tokenStorage;
22 $this->lifeTime
= $lifeTime;
25 public function getFilters()
28 new \
Twig_SimpleFilter('removeWww', [$this, 'removeWww']),
32 public function getFunctions()
35 new \
Twig_SimpleFunction('count_entries', [$this, 'countEntries']),
36 new \
Twig_SimpleFunction('count_tags', [$this, 'countTags']),
40 public function removeWww($url)
42 return preg_replace('/^www\./i', '', $url);
46 * Return number of entries depending of the type (unread, archive, starred or all).
48 * @param string $type Type of entries to count
52 public function countEntries($type)
54 $user = $this->tokenStorage
->getToken() ? $this->tokenStorage
->getToken()->getUser() : null;
56 if (null === $user || !is_object($user)) {
62 $qb = $this->entryRepository
->getBuilderForStarredByUser($user->getId());
66 $qb = $this->entryRepository
->getBuilderForArchiveByUser($user->getId());
70 $qb = $this->entryRepository
->getBuilderForUnreadByUser($user->getId());
74 $qb = $this->entryRepository
->getBuilderForAllByUser($user->getId());
78 throw new \
InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type));
81 // THANKS to PostgreSQL we CAN'T make a DEAD SIMPLE count(e.id)
82 // ERROR: column "e0_.id" must appear in the GROUP BY clause or be used in an aggregate function
88 $data = $this->enableCache($query)
95 * Return number of tags.
99 public function countTags()
101 $user = $this->tokenStorage
->getToken() ? $this->tokenStorage
->getToken()->getUser() : null;
103 if (null === $user || !is_object($user)) {
107 $qb = $this->tagRepository
->findAllTags($user->getId());
109 $data = $this->enableCache($qb->getQuery())
116 * Enable cache for a query.
118 * @param Query $query
122 private function enableCache(Query
$query)
124 $query->useQueryCache(true);
125 $query->useResultCache(true);
126 $query->setResultCacheLifetime($this->lifeTime
);
131 public function getName()
133 return 'wallabag_extension';