]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Twig/WallabagExtension.php
CS
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Twig / WallabagExtension.php
1 <?php
2
3 namespace Wallabag\CoreBundle\Twig;
4
5 use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
6 use Wallabag\CoreBundle\Repository\EntryRepository;
7
8 class WallabagExtension extends \Twig_Extension implements \Twig_Extension_GlobalsInterface
9 {
10 private $tokenStorage;
11 private $repository;
12
13 public function __construct(EntryRepository $repository = null, TokenStorageInterface $tokenStorage = null)
14 {
15 $this->repository = $repository;
16 $this->tokenStorage = $tokenStorage;
17 }
18
19 public function getFilters()
20 {
21 return [
22 new \Twig_SimpleFilter('removeWww', [$this, 'removeWww']),
23 ];
24 }
25
26 public function getFunctions()
27 {
28 return array(
29 new \Twig_SimpleFunction('count_entries', [$this, 'countEntries']),
30 );
31 }
32
33 public function removeWww($url)
34 {
35 return preg_replace('/^www\./i', '', $url);
36 }
37
38 /**
39 * Return number of entries depending of the type (unread, archive, starred or all).
40 *
41 * @param string $type Type of entries to count
42 *
43 * @return int
44 */
45 public function countEntries($type)
46 {
47 $user = $this->tokenStorage->getToken() ? $this->tokenStorage->getToken()->getUser() : null;
48
49 if (null === $user || !is_object($user)) {
50 return [];
51 }
52
53 switch ($type) {
54 case 'starred':
55 $qb = $this->repository->getBuilderForStarredByUser($user->getId());
56 break;
57
58 case 'archive':
59 $qb = $this->repository->getBuilderForArchiveByUser($user->getId());
60 break;
61
62 case 'unread':
63 $qb = $this->repository->getBuilderForUnreadByUser($user->getId());
64 break;
65
66 case 'all':
67 $qb = $this->repository->getBuilderForAllByUser($user->getId());
68 break;
69
70 default:
71 throw new \InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type));
72 }
73
74 // THANKS to PostgreSQL we CAN'T make a DEAD SIMPLE count(e.id)
75 // ERROR: column "e0_.id" must appear in the GROUP BY clause or be used in an aggregate function
76 $query = $qb
77 ->select('e.id')
78 ->groupBy('e.id')
79 ->getQuery();
80
81 $data = $this->repository
82 ->enableCache($query)
83 ->getArrayResult();
84
85 return count($data);
86 }
87
88 public function getName()
89 {
90 return 'wallabag_extension';
91 }
92 }