Completed
Push — master ( 16b193...f4f799 )
by Nicolas
05:41 queued 03:01
created

WallabagExtension::removeSchemeAndWww()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
namespace Wallabag\CoreBundle\Twig;
4
5
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
6
use Symfony\Component\Translation\TranslatorInterface;
7
use Wallabag\CoreBundle\Repository\EntryRepository;
8
use Wallabag\CoreBundle\Repository\TagRepository;
9
10
class WallabagExtension extends \Twig_Extension implements \Twig_Extension_GlobalsInterface
11
{
12
    private $tokenStorage;
13
    private $entryRepository;
14
    private $tagRepository;
15
    private $lifeTime;
16
    private $translator;
17
18
    public function __construct(EntryRepository $entryRepository, TagRepository $tagRepository, TokenStorageInterface $tokenStorage, $lifeTime, TranslatorInterface $translator)
19
    {
20
        $this->entryRepository = $entryRepository;
21
        $this->tagRepository = $tagRepository;
22
        $this->tokenStorage = $tokenStorage;
23
        $this->lifeTime = $lifeTime;
24
        $this->translator = $translator;
25
    }
26
27
    public function getFilters()
28
    {
29
        return [
30
            new \Twig_SimpleFilter('removeWww', [$this, 'removeWww']),
31
            new \Twig_SimpleFilter('removeSchemeAndWww', [$this, 'removeSchemeAndWww']),
32
        ];
33
    }
34
35
    public function getFunctions()
36
    {
37
        return [
38
            new \Twig_SimpleFunction('count_entries', [$this, 'countEntries']),
39
            new \Twig_SimpleFunction('count_tags', [$this, 'countTags']),
40
            new \Twig_SimpleFunction('display_stats', [$this, 'displayStats']),
41
        ];
42
    }
43
44
    public function removeWww($url)
45
    {
46
        return preg_replace('/^www\./i', '', $url);
47
    }
48
49
    public function removeSchemeAndWww($url)
50
    {
51
        return $this->removeWww(
52
            preg_replace('@^https?://@i', '', $url)
53
        );
54
    }
55
56
    /**
57
     * Return number of entries depending of the type (unread, archive, starred or all).
58
     *
59
     * @param string $type Type of entries to count
60
     *
61
     * @return int
62
     */
63
    public function countEntries($type)
64
    {
65
        $user = $this->tokenStorage->getToken() ? $this->tokenStorage->getToken()->getUser() : null;
66
67
        if (null === $user || !is_object($user)) {
68
            return 0;
69
        }
70
71
        switch ($type) {
72
            case 'starred':
73
                $qb = $this->entryRepository->getBuilderForStarredByUser($user->getId());
74
                break;
75
            case 'archive':
76
                $qb = $this->entryRepository->getBuilderForArchiveByUser($user->getId());
77
                break;
78
            case 'unread':
79
                $qb = $this->entryRepository->getBuilderForUnreadByUser($user->getId());
80
                break;
81
            case 'all':
82
                $qb = $this->entryRepository->getBuilderForAllByUser($user->getId());
83
                break;
84
            default:
85
                throw new \InvalidArgumentException(sprintf('Type "%s" is not implemented.', $type));
86
        }
87
88
        // THANKS to PostgreSQL we CAN'T make a DEAD SIMPLE count(e.id)
89
        // ERROR: column "e0_.id" must appear in the GROUP BY clause or be used in an aggregate function
90
        $query = $qb
91
            ->select('e.id')
92
            ->groupBy('e.id')
93
            ->getQuery();
94
95
        $query->useQueryCache(true);
96
        $query->useResultCache(true);
97
        $query->setResultCacheLifetime($this->lifeTime);
98
99
        return count($query->getArrayResult());
100
    }
101
102
    /**
103
     * Return number of tags.
104
     *
105
     * @return int
106
     */
107
    public function countTags()
108
    {
109
        $user = $this->tokenStorage->getToken() ? $this->tokenStorage->getToken()->getUser() : null;
110
111
        if (null === $user || !is_object($user)) {
112
            return 0;
113
        }
114
115
        return $this->tagRepository->countAllTags($user->getId());
116
    }
117
118
    /**
119
     * Display a single line about reading stats.
120
     *
121
     * @return string
122
     */
123
    public function displayStats()
124
    {
125
        $user = $this->tokenStorage->getToken() ? $this->tokenStorage->getToken()->getUser() : null;
126
127
        if (null === $user || !is_object($user)) {
128
            return 0;
129
        }
130
131
        $query = $this->entryRepository->getBuilderForArchiveByUser($user->getId())
132
            ->select('e.id')
133
            ->groupBy('e.id')
134
            ->getQuery();
135
136
        $query->useQueryCache(true);
137
        $query->useResultCache(true);
138
        $query->setResultCacheLifetime($this->lifeTime);
139
140
        $nbArchives = count($query->getArrayResult());
141
142
        $interval = $user->getCreatedAt()->diff(new \DateTime('now'));
143
        $nbDays = (int) $interval->format('%a') ?: 1;
144
145
        // force setlocale for date translation
146
        setlocale(LC_TIME, strtolower($user->getConfig()->getLanguage()) . '_' . strtoupper(strtolower($user->getConfig()->getLanguage())));
147
148
        return $this->translator->trans('footer.stats', [
149
            '%user_creation%' => strftime('%e %B %Y', $user->getCreatedAt()->getTimestamp()),
150
            '%nb_archives%' => $nbArchives,
151
            '%per_day%' => round($nbArchives / $nbDays, 2),
152
        ]);
153
    }
154
155
    public function getName()
156
    {
157
        return 'wallabag_extension';
158
    }
159
}
160