]> Raphaël G. Git Repositories - blogbundle/blob - Controller/DefaultController.php
Add validators translations
[blogbundle] / Controller / DefaultController.php
1 <?php declare(strict_types=1);
2
3 /*
4 * This file is part of the Rapsys BlogBundle package.
5 *
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Rapsys\BlogBundle\Controller;
13
14 use Symfony\Component\HttpFoundation\Request;
15 use Symfony\Component\HttpFoundation\Response;
16
17 use Rapsys\BlogBundle\Entity\Article;
18
19 /**
20 * {@inheritdoc}
21 */
22 class DefaultController extends AbstractController {
23 /**
24 * The contact page
25 *
26 * @desc Send a contact mail to configured contact
27 *
28 * @param Request $request The request instance
29 * @return Response The rendered view or redirection
30 */
31 public function contact(Request $request): Response {
32 //Set title
33 $this->context['title'] = $this->translator->trans('Contact');
34
35 //Set description
36 $this->context['description'] = $this->translator->trans('Welcome to raphaël\'s developer diary contact page');
37
38 //Set keywords
39 $this->context['keywords'] = $this->translator->trans('contact');
40
41 //Set data
42 $data = [];
43
44 //With user
45 if ($user = $this->getUser()) {
46 //Set data
47 $data = [
48 'name' => $user->getRecipientName(),
49 'mail' => $user->getMail()
50 ];
51 }
52
53 //Create the form according to the FormType created previously.
54 //And give the proper parameters
55 $form = $this->createForm('Rapsys\BlogBundle\Form\ContactType', $data, [
56 'action' => $this->generateUrl('rapsys_blog_contact'),
57 'method' => 'POST'
58 ]);
59
60 if ($request->isMethod('POST')) {
61 // Refill the fields in case the form is not valid.
62 $form->handleRequest($request);
63
64 if ($form->isSubmitted() && $form->isValid()) {
65 //Get data
66 $data = $form->getData();
67
68 //Create message
69 $message = (new TemplatedEmail())
70 //Set sender
71 ->from(new Address($data['mail'], $data['name']))
72 //Set recipient
73 ->to(new Address($this->config['contact']['mail'], $this->config['contact']['title']))
74 //Set subject
75 ->subject($data['subject'])
76
77 //Set path to twig templates
78 ->htmlTemplate('@RapsysBlog/mail/contact.html.twig')
79 ->textTemplate('@RapsysBlog/mail/contact.text.twig')
80
81 //Set context
82 ->context(
83 [
84 'subject' => $data['subject'],
85 'message' => strip_tags($data['message']),
86 ]+$this->context
87 );
88
89 //Try sending message
90 //XXX: mail delivery may silently fail
91 try {
92 //Send message
93 $this->mailer->send($message);
94
95 //Redirect on the same route with sent=1 to cleanup form
96 return $this->redirectToRoute($request->get('_route'), ['sent' => 1]+$request->get('_route_params'));
97 //Catch obvious transport exception
98 } catch(TransportExceptionInterface $e) {
99 if ($message = $e->getMessage()) {
100 //Add error message mail unreachable
101 $form->get('mail')->addError(new FormError($this->translator->trans('Unable to contact: %mail%: %message%', ['%mail%' => $this->config['contact']['mail'], '%message%' => $this->translator->trans($message)])));
102 } else {
103 //Add error message mail unreachable
104 $form->get('mail')->addError(new FormError($this->translator->trans('Unable to contact: %mail%', ['%mail%' => $this->config['contact']['mail']])));
105 }
106 }
107 }
108 }
109
110 //Render template
111 #return $this->render('@RapsysAir/form/contact.html.twig', ['form' => $form->createView(), 'sent' => $request->query->get('sent', 0)]+$this->context);
112 return $this->render('@RapsysBlog/contact.html.twig', $this->context, $response);
113 }
114
115 /**
116 * The index page
117 *
118 * Display articles
119 *
120 * @param Request $request The request instance
121 * @return Response The rendered view
122 */
123 public function index(Request $request): Response {
124 //With articles
125 if ($count = $this->doctrine->getRepository(Article::class)->findCountAsInt()) {
126 //Negative page or over page
127 if (($page = (int) $request->get('page', 0)) < 0 || $page > $count / $this->limit) {
128 //Throw 404
129 throw $this->createNotFoundException($this->translator->trans('Unable to find articles (page: %page%)', ['%page%' => $page]));
130 }
131
132 //Without articles
133 if (empty($this->context['articles'] = $this->doctrine->getRepository(Article::class)->findAllAsArray($page, $this->limit))) {
134 //Throw 404
135 throw $this->createNotFoundException($this->translator->trans('Unable to find articles'));
136 }
137
138 //With prev link
139 if ($page > 0) {
140 //Set articles older
141 $this->context['head']['prev'] = $this->context['articles_prev'] = $this->generateUrl($request->attributes->get('_route'), ['page' => $page - 1]+$request->attributes->get('_route_params'));
142 }
143
144 //With next link
145 if ($count > ($page + 1) * $this->limit) {
146 //Set articles newer
147 $this->context['head']['next'] = $this->context['articles_next'] = $this->generateUrl($request->attributes->get('_route'), ['page' => $page + 1]+$request->attributes->get('_route_params'));
148 }
149
150 //Set modified
151 $this->modified = max(array_map(function ($v) { return $v['modified']; }, $this->context['articles']));
152 //Without articles
153 } else {
154 //Set empty articles
155 $this->context['articles'] = [];
156
157 //Set empty modified
158 $this->modified = new \DateTime('-1 year');
159 }
160
161 //Create response
162 $response = new Response();
163
164 //With logged user
165 if ($this->checker->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
166 //Set last modified
167 $response->setLastModified(new \DateTime('-1 year'));
168
169 //Set as private
170 $response->setPrivate();
171 //Without logged user
172 } else {
173 //Set etag
174 //XXX: only for public to force revalidation by last modified
175 $response->setEtag(md5(serialize($this->context['articles'])));
176
177 //Set last modified
178 $response->setLastModified($this->modified);
179
180 //Set as public
181 $response->setPublic();
182
183 //Without role and modification
184 if ($response->isNotModified($request)) {
185 //Return 304 response
186 return $response;
187 }
188 }
189
190 //Set keywords
191 $this->context['head']['keywords'] = implode(
192 ', ',
193 //Use closure to extract each unique article keywords sorted
194 (function ($t) {
195 //Return array
196 $r = [];
197
198 //Iterate on articles
199 foreach($t as $a) {
200 //Non empty keywords
201 if (!empty($a['keywords'])) {
202 //Iterate on keywords
203 foreach($a['keywords'] as $k) {
204 //Set keyword
205 $r[$k['title']] = $k['title'];
206 }
207 }
208 }
209
210 //Sort array
211 sort($r);
212
213 //Return array
214 return $r;
215 })($this->context['articles'])
216 );
217
218 //Set title
219 $this->context['title'] = $this->translator->trans('Home');
220
221 //Set description
222 $this->context['description'] = $this->translator->trans('Welcome to raphaël\'s developer diary');
223
224 //Render the view
225 return $this->render('@RapsysBlog/index.html.twig', $this->context, $response);
226 }
227 }