Passed
Pull Request — master (#94)
by Alexis
07:17
created

DefaultController::resetCookieAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 6
cts 6
cp 1
rs 9.8333
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
namespace AlexisLefebvre\Bundle\AsyncTweetsBundle\Controller;
4
5
use AlexisLefebvre\Bundle\AsyncTweetsBundle\Entity\Tweet;
6
use AlexisLefebvre\Bundle\AsyncTweetsBundle\Entity\TweetRepository;
7
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController as BaseController;
8
use Symfony\Component\HttpFoundation\Cookie;
9
use Symfony\Component\HttpFoundation\RedirectResponse;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\HttpFoundation\Response;
12
use Symfony\Component\HttpFoundation\Session\Session;
13
14
// Compatibility layer for Symfony 3.4
15
if (!class_exists('Symfony\Bundle\FrameworkBundle\Controller\Controller')) {
16
    class_alias('Symfony\Bundle\FrameworkBundle\Controller\Controller', 'Symfony\Bundle\FrameworkBundle\Controller\AbstractController');
17
}
18
19
class DefaultController extends BaseController
20
{
21
    /** @var TweetRepository */
22
    private $tweetRepository;
23
24 7
    public function indexAction(Request $request, ?string $firstTweetId): Response
25
    {
26
        /** @var TweetRepository $tweetRepository */
27 7
        $tweetRepository = $this->getDoctrine()
28 7
            ->getRepository('AsyncTweetsBundle:Tweet');
29
30 7
        $this->tweetRepository = $tweetRepository;
31
32 7
        $tweets = $this->tweetRepository
33 7
            ->getWithUsersAndMedias($firstTweetId);
34
35 7
        $variables = $this->getVariables($request, $tweets, $firstTweetId);
36
37 7
        $response = $this->render(
38 7
            'AsyncTweetsBundle:Default:index.html.twig',
39
            [
40 7
                'tweets' => $tweets,
41 7
                'vars'   => $variables,
42
            ]
43
        );
44
45 7
        if (!is_null($variables['cookie'])) {
46 6
            $response->headers->setCookie($variables['cookie']);
47
        }
48
49 7
        return $response;
50
    }
51
52
    /**
53
     * @param Request $request
54
     * @param Tweet[] $tweets
55
     * @param string  $firstTweetId
56
     *
57
     * @return array $vars
58
     */
59 7
    private function getVariables(Request $request, $tweets, ?string $firstTweetId): array
60
    {
61
        $vars = [
62 7
            'first'    => $firstTweetId,
63
            'previous' => null,
64
            'next'     => null,
65 7
            'number'   => 0,
66 7
            'cookieId' => $this->getLastTweetIdFromCookie($request),
67
            // No cookie by default
68
            'cookie' => null,
69
        ];
70
71 7
        if (count($tweets) > 0) {
72 6
            $vars = $this->getTweetsVars($tweets, $vars);
73
        }
74
75 7
        return $vars;
76
    }
77
78
    /**
79
     * If a Tweet is displayed, fetch data from repository.
80
     *
81
     * @param Tweet[] $tweets
82
     * @param array   $vars
83
     */
84 6
    private function getTweetsVars($tweets, array $vars): array
85
    {
86
        /** @var string $firstTweetId */
87 6
        $firstTweetId = $tweets[0]->getId();
88
89 6
        $vars['previous'] = $this->tweetRepository
90 6
            ->getPreviousTweetId($firstTweetId);
91 6
        $vars['next'] = $this->tweetRepository
92 6
            ->getNextTweetId($firstTweetId);
93
94
        // Only update the cookie if the last Tweet Id is bigger than
95
        //  the one in the cookie
96 6
        if ($firstTweetId > $vars['cookieId']) {
97 6
            $vars['cookie'] = $this->createCookie($firstTweetId);
98 6
            $vars['cookieId'] = $firstTweetId;
99
        }
100
101 6
        $vars['number'] = $this->tweetRepository
102 6
            ->countPendingTweets($vars['cookieId']);
103
104 6
        $vars['first'] = $firstTweetId;
105
106 6
        return $vars;
107
    }
108
109 7
    private function getLastTweetIdFromCookie(Request $request)
110
    {
111 7
        if ($request->cookies->has('lastTweetId')) {
112 4
            return $request->cookies->get('lastTweetId');
113
        }
114
        // else
115 7
    }
116
117 6
    private function createCookie(string $firstTweetId): Cookie
118
    {
119 6
        $nextYear = new \DateTime('now');
120 6
        $nextYear->add(new \DateInterval('P1Y'));
121
122
        // Set last Tweet Id
123 6
        $cookie = new Cookie(
124 6
            'lastTweetId',
125 6
            $firstTweetId,
126 6
            $nextYear->format('U')
127
        );
128
129 6
        return $cookie;
130
    }
131
132 1
    public function resetCookieAction(): RedirectResponse
133
    {
134
        /* @see http://www.craftitonline.com/2011/07/symfony2-how-to-set-a-cookie/ */
135 1
        $response = new RedirectResponse(
136 1
            $this->generateUrl('asynctweets_homepage')
137
        );
138
139
        // Reset last Tweet Id
140 1
        $cookie = new Cookie('lastTweetId', null);
141 1
        $response->headers->setCookie($cookie);
142
143 1
        return $response;
144
    }
145
146 2
    public function deleteLessThanAction(Request $request): RedirectResponse
147
    {
148 2
        $lastTweetId = $this->getLastTweetIdFromCookie($request);
149
150 2
        if (!is_null($lastTweetId)) {
151
            /** @var TweetRepository $tweetRepository */
152 2
            $tweetRepository = $this->getDoctrine()
153 2
                ->getRepository('AsyncTweetsBundle:Tweet');
154
155
            $count = $tweetRepository
156 2
                ->deleteAndHideTweetsLessThanId($lastTweetId);
157
158
            /** @var Session $session */
159 2
            $session = $this->get('session');
160
161 2
            $session->getFlashBag()->add(
162 2
                'message',
163 2
                sprintf('%s tweets deleted.', $count)
164
            );
165
        }
166
167 2
        return $this->redirect($this->generateUrl('asynctweets_homepage'));
168
    }
169
}
170