]> Raphaƫl G. Git Repositories - airbundle/blob - Controller/SnippetController.php
Remove vote feature
[airbundle] / Controller / SnippetController.php
1 <?php
2
3 namespace Rapsys\AirBundle\Controller;
4
5 use Symfony\Component\HttpFoundation\Request;
6 use Symfony\Component\Routing\RequestContext;
7 use Symfony\Component\Routing\Exception\MethodNotAllowedException;
8 use Symfony\Component\Routing\Exception\ResourceNotFoundException;
9 use Rapsys\AirBundle\Entity\Location;
10 use Rapsys\AirBundle\Entity\Snippet;
11 use Rapsys\AirBundle\Entity\User;
12
13 class SnippetController extends DefaultController {
14 /**
15 * Add snippet
16 *
17 * @desc Persist snippet in database
18 *
19 * @param Request $request The request instance
20 *
21 * @return Response The rendered view or redirection
22 *
23 * @throws \RuntimeException When user has not at least guest role
24 */
25 public function add(Request $request) {
26 //Prevent non-guest to access here
27 $this->denyAccessUnlessGranted('ROLE_GUEST', null, $this->translator->trans('Unable to access this page without role %role%!', ['%role%' => $this->translator->trans('Guest')]));
28
29 //Create ApplicationType form
30 $form = $this->createForm('Rapsys\AirBundle\Form\SnippetType', null, [
31 //Set the action
32 'action' => $this->generateUrl('rapsys_air_snippet_add'),
33 //Set the form attribute
34 'attr' => []
35 ]);
36
37 //Refill the fields in case of invalid form
38 $form->handleRequest($request);
39
40 //Prevent creating snippet for other user unless admin
41 if ($form->get('user')->getData() !== $this->getUser()) {
42 //Prevent non-admin to access here
43 $this->denyAccessUnlessGranted('ROLE_ADMIN', null, $this->translator->trans('Unable to access this page without role %role%!', ['%role%' => $this->translator->trans('Admin')]));
44 }
45
46 //Handle invalid form
47 if (!$form->isSubmitted() || !$form->isValid()) {
48 //Set section
49 $section = $this->translator->trans('Snippet add');
50
51 //Set title
52 $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
53
54 //Render the view
55 return $this->render('@RapsysAir/snippet/add.html.twig', ['title' => $title, 'section' => $section, 'form' => $form->createView()]+$this->context);
56 }
57
58 //Get doctrine
59 $doctrine = $this->getDoctrine();
60
61 //Get manager
62 $manager = $doctrine->getManager();
63
64 //Get snippet
65 $snippet = $form->getData();
66
67 //Set created
68 $snippet->setCreated(new \DateTime('now'));
69
70 //Set updated
71 $snippet->setUpdated(new \DateTime('now'));
72
73 //Queue snippet save
74 $manager->persist($snippet);
75
76 //Flush to get the ids
77 $manager->flush();
78
79 //Add notice
80 $this->addFlash('notice', $this->translator->trans('Snippet in %locale% %location% for %user% created', ['%locale%' => $snippet->getLocale(), '%location%' => $this->translator->trans('at '.$snippet->getLocation()), '%user%' => $snippet->getUser()]));
81
82 //Extract and process referer
83 if ($referer = $request->headers->get('referer')) {
84 //Create referer request instance
85 $req = Request::create($referer);
86
87 //Get referer path
88 $path = $req->getPathInfo();
89
90 //Get referer query string
91 $query = $req->getQueryString();
92
93 //Remove script name
94 $path = str_replace($request->getScriptName(), '', $path);
95
96 //Try with referer path
97 try {
98 //Save old context
99 $oldContext = $this->router->getContext();
100
101 //Force clean context
102 //XXX: prevent MethodNotAllowedException because current context method is POST in onevendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php+42
103 $this->router->setContext(new RequestContext());
104
105 //Retrieve route matching path
106 $route = $this->router->match($path);
107
108 //Reset context
109 $this->router->setContext($oldContext);
110
111 //Clear old context
112 unset($oldContext);
113
114 //Extract name
115 $name = $route['_route'];
116
117 //Remove route and controller from route defaults
118 unset($route['_route'], $route['_controller']);
119
120 //Check if snippet view route
121 if ($name == 'rapsys_air_organizer_view' && !empty($route['id'])) {
122 //Replace id
123 $route['id'] = $snippet->getUser()->getId();
124 //Other routes
125 } else {
126 //Set snippet
127 $route['snippet'] = $snippet->getId();
128 }
129
130 //Generate url
131 return $this->redirectToRoute($name, $route);
132 //No route matched
133 } catch(MethodNotAllowedException|ResourceNotFoundException $e) {
134 //Unset referer to fallback to default route
135 unset($referer);
136 }
137 }
138
139 //Redirect to cleanup the form
140 return $this->redirectToRoute('rapsys_air', ['snippet' => $snippet->getId()]);
141 }
142
143 /**
144 * Edit snippet
145 *
146 * @desc Persist snippet in database
147 *
148 * @param Request $request The request instance
149 *
150 * @return Response The rendered view or redirection
151 *
152 * @throws \RuntimeException When user has not at least guest role
153 */
154 public function edit(Request $request, $id) {
155 //Prevent non-guest to access here
156 $this->denyAccessUnlessGranted('ROLE_GUEST', null, $this->translator->trans('Unable to access this page without role %role%!', ['%role%' => $this->translator->trans('Guest')]));
157
158 //Get doctrine
159 $doctrine = $this->getDoctrine();
160
161 //Get snippet
162 if (empty($snippet = $doctrine->getRepository(Snippet::class)->findOneById($id))) {
163 throw $this->createNotFoundException($this->translator->trans('Unable to find snippet: %id%', ['%id%' => $id]));
164 }
165
166 //Create ApplicationType form
167 $form = $this->createForm('Rapsys\AirBundle\Form\SnippetType', $snippet, [
168 //Set the action
169 'action' => $this->generateUrl('rapsys_air_snippet_edit', ['id' => $id]),
170 //Set the form attribute
171 'attr' => []
172 ]);
173
174 //Refill the fields in case of invalid form
175 $form->handleRequest($request);
176
177 //Prevent creating snippet for other user unless admin
178 if ($form->get('user')->getData() !== $this->getUser()) {
179 //Prevent non-admin to access here
180 $this->denyAccessUnlessGranted('ROLE_ADMIN', null, $this->translator->trans('Unable to access this page without role %role%!', ['%role%' => $this->translator->trans('Admin')]));
181 }
182
183 //Handle invalid form
184 if (!$form->isSubmitted() || !$form->isValid()) {
185 //Set section
186 $section = $this->translator->trans('Snippet %id%', ['%id%' => $id]);
187
188 //Set title
189 $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
190
191 //Render the view
192 return $this->render('@RapsysAir/snippet/edit.html.twig', ['id' => $id, 'title' => $title, 'section' => $section, 'form' => $form->createView()]+$this->context);
193 }
194
195 //Get manager
196 $manager = $doctrine->getManager();
197
198 //Set updated
199 $snippet->setUpdated(new \DateTime('now'));
200
201 //Queue snippet save
202 $manager->persist($snippet);
203
204 //Flush to get the ids
205 $manager->flush();
206
207 //Add notice
208 $this->addFlash('notice', $this->translator->trans('Snippet %id% in %locale% %location% for %user% updated', ['%id%' => $id, '%locale%' => $snippet->getLocale(), '%location%' => $this->translator->trans('at '.$snippet->getLocation()), '%user%' => $snippet->getUser()]));
209
210 //Extract and process referer
211 if ($referer = $request->headers->get('referer')) {
212 //Create referer request instance
213 $req = Request::create($referer);
214
215 //Get referer path
216 $path = $req->getPathInfo();
217
218 //Get referer query string
219 $query = $req->getQueryString();
220
221 //Remove script name
222 $path = str_replace($request->getScriptName(), '', $path);
223
224 //Try with referer path
225 try {
226 //Save old context
227 $oldContext = $this->router->getContext();
228
229 //Force clean context
230 //XXX: prevent MethodNotAllowedException because current context method is POST in onevendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php+42
231 $this->router->setContext(new RequestContext());
232
233 //Retrieve route matching path
234 $route = $this->router->match($path);
235
236 //Reset context
237 $this->router->setContext($oldContext);
238
239 //Clear old context
240 unset($oldContext);
241
242 //Extract name
243 $name = $route['_route'];
244
245 //Remove route and controller from route defaults
246 unset($route['_route'], $route['_controller']);
247
248 //Check if snippet view route
249 if ($name == 'rapsys_air_organizer_view' && !empty($route['id'])) {
250 //Replace id
251 $route['id'] = $snippet->getUser()->getId();
252 //Other routes
253 } else {
254 //Set snippet
255 $route['snippet'] = $snippet->getId();
256 }
257
258 //Generate url
259 return $this->redirectToRoute($name, $route);
260 //No route matched
261 } catch(MethodNotAllowedException|ResourceNotFoundException $e) {
262 //Unset referer to fallback to default route
263 unset($referer);
264 }
265 }
266
267 //Redirect to cleanup the form
268 return $this->redirectToRoute('rapsys_air', ['snippet' => $snippet->getId()]);
269 }
270 }