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