3 namespace Rapsys\AirBundle\Controller
;
5 use Symfony\Component\Filesystem\Exception\IOExceptionInterface
;
6 use Symfony\Component\Filesystem\Filesystem
;
7 use Symfony\Component\HttpFoundation\File\Exception\FileException
;
8 use Symfony\Component\HttpFoundation\Request
;
9 use Symfony\Component\HttpFoundation\Response
;
10 use Symfony\Component\Routing\Exception\MethodNotAllowedException
;
11 use Symfony\Component\Routing\Exception\ResourceNotFoundException
;
12 use Symfony\Component\Routing\RequestContext
;
14 use Rapsys\AirBundle\Entity\Location
;
15 use Rapsys\AirBundle\Entity\Snippet
;
16 use Rapsys\AirBundle\Entity\User
;
18 class SnippetController
extends DefaultController
{
22 * @desc Persist snippet in database
24 * @param Request $request The request instance
26 * @return Response The rendered view or redirection
28 * @throws \RuntimeException When user has not at least guest role
30 public function add(Request
$request) {
31 //Prevent non-guest to access here
32 $this->denyAccessUnlessGranted('ROLE_GUEST', null, $this->translator
->trans('Unable to access this page without role %role%!', ['%role%' => $this->translator
->trans('Guest')]));
34 //Create SnippetType form
35 $form = $this->container
->get('form.factory')->createNamed(
37 'snipped_'.$request->getLocale().'_'.$request->get('location'),
39 'Rapsys\AirBundle\Form\SnippetType',
45 'action' => $this->generateUrl('rapsys_air_snippet_add', ['location' => $request->get('location')]),
46 //Set the form attribute
51 //Refill the fields in case of invalid form
52 $form->handleRequest($request);
54 //Prevent creating snippet for other user unless admin
55 if ($form->get('user')->getData() !== $this->getUser()) {
56 //Prevent non-admin to access here
57 $this->denyAccessUnlessGranted('ROLE_ADMIN', null, $this->translator
->trans('Unable to access this page without role %role%!', ['%role%' => $this->translator
->trans('Admin')]));
61 if (!$form->isSubmitted() || !$form->isValid()) {
63 $section = $this->translator
->trans('Snippet add');
66 $title = $this->translator
->trans($this->config
['site']['title']).' - '.$section;
69 return $this->render('@RapsysAir/snippet/add.html.twig', ['title' => $title, 'section' => $section, 'form' => $form->createView()]+
$this->context
);
73 $doctrine = $this->getDoctrine();
76 $manager = $doctrine->getManager();
79 $snippet = $form->getData();
82 $snippet->setCreated(new \
DateTime('now'));
85 $snippet->setUpdated(new \
DateTime('now'));
88 $manager->persist($snippet);
90 //Flush to get the ids
94 $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()]));
96 //Extract and process referer
97 if ($referer = $request->headers
->get('referer')) {
98 //Create referer request instance
99 $req = Request
::create($referer);
102 $path = $req->getPathInfo();
104 //Get referer query string
105 $query = $req->getQueryString();
108 $path = str_replace($request->getScriptName(), '', $path);
110 //Try with referer path
113 $oldContext = $this->router
->getContext();
115 //Force clean context
116 //XXX: prevent MethodNotAllowedException because current context method is POST in onevendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php+42
117 $this->router
->setContext(new RequestContext());
119 //Retrieve route matching path
120 $route = $this->router
->match($path);
123 $this->router
->setContext($oldContext);
129 $name = $route['_route'];
131 //Remove route and controller from route defaults
132 unset($route['_route'], $route['_controller']);
134 //Check if snippet view route
135 if ($name == 'rapsys_air_user_view' && !empty($route['id'])) {
137 $route['id'] = $snippet->getUser()->getId();
141 $route['snippet'] = $snippet->getId();
145 return $this->redirectToRoute($name, $route);
147 } catch(MethodNotAllowedException
|ResourceNotFoundException
$e) {
148 //Unset referer to fallback to default route
153 //Redirect to cleanup the form
154 return $this->redirectToRoute('rapsys_air', ['snippet' => $snippet->getId()]);
160 * @desc Persist snippet in database
162 * @param Request $request The request instance
164 * @return Response The rendered view or redirection
166 * @throws \RuntimeException When user has not at least guest role
168 public function edit(Request
$request, $id) {
169 //Prevent non-guest to access here
170 $this->denyAccessUnlessGranted('ROLE_GUEST', null, $this->translator
->trans('Unable to access this page without role %role%!', ['%role%' => $this->translator
->trans('Guest')]));
173 $doctrine = $this->getDoctrine();
176 if (empty($snippet = $doctrine->getRepository(Snippet
::class)->findOneById($id))) {
177 throw $this->createNotFoundException($this->translator
->trans('Unable to find snippet: %id%', ['%id%' => $id]));
180 //Create SnippetType form
181 $form = $this->container
->get('form.factory')->createNamed(
183 'snipped_'.$request->getLocale().'_'.$snippet->getLocation()->getId(),
185 'Rapsys\AirBundle\Form\SnippetType',
191 'action' => $this->generateUrl('rapsys_air_snippet_edit', ['id' => $id]),
192 //Set the form attribute
197 //Refill the fields in case of invalid form
198 $form->handleRequest($request);
200 //Prevent creating snippet for other user unless admin
201 if ($form->get('user')->getData() !== $this->getUser()) {
202 //Prevent non-admin to access here
203 $this->denyAccessUnlessGranted('ROLE_ADMIN', null, $this->translator
->trans('Unable to access this page without role %role%!', ['%role%' => $this->translator
->trans('Admin')]));
206 //Handle invalid form
207 if (!$form->isSubmitted() || !$form->isValid()) {
209 $section = $this->translator
->trans('Snippet %id%', ['%id%' => $id]);
212 $title = $this->translator
->trans($this->config
['site']['title']).' - '.$section;
215 return $this->render('@RapsysAir/snippet/edit.html.twig', ['id' => $id, 'title' => $title, 'section' => $section, 'form' => $form->createView()]+
$this->context
);
219 //TODO: add delete button ???
220 if ($image = $form->get('image')->getData()) {
222 #$public = $this->container->get('kernel')->getBundle('RapsysAirBundle')->getPath().'/Resources/public';
223 #$public = $this->container->get('kernel')->locateResource('@RapsysAirBundle/Resources/public');
224 $public = $this->getPublicPath();
226 //Create imagick object
227 $imagick = new \
Imagick();
230 $imagick->readImage($image->getRealPath());
233 //XXX: uploaded path location/<userId>/<locationId>.png and session image location/<userId>/<locationId>/<sessionId>.jpeg
234 //XXX: default path location/default.png and session location/default/<sessionId>.jpeg
235 $destination = $public.'/location/'.$snippet->getUser()->getId().'/'.$snippet->getLocation()->getId().'.png';
237 //Check target directory
238 if (!is_dir($dir = dirname($destination))) {
239 //Create filesystem object
240 $filesystem = new Filesystem();
244 //XXX: set as 0775, symfony umask (0022) will reduce rights (0755)
245 $filesystem->mkdir($dir, 0775);
246 } catch (IOExceptionInterface
$e) {
248 throw new \
Exception(sprintf('Output directory "%s" do not exists and unable to create it', $dir), 0, $e);
253 if (!$imagick->writeImage($destination)) {
255 throw new \
Exception(sprintf('Unable to write image "%s"', $destination));
260 $manager = $doctrine->getManager();
263 $snippet->setUpdated(new \
DateTime('now'));
266 $manager->persist($snippet);
268 //Flush to get the ids
272 $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()]));
274 //Extract and process referer
275 if ($referer = $request->headers
->get('referer')) {
276 //Create referer request instance
277 $req = Request
::create($referer);
280 $path = $req->getPathInfo();
282 //Get referer query string
283 $query = $req->getQueryString();
286 $path = str_replace($request->getScriptName(), '', $path);
288 //Try with referer path
291 $oldContext = $this->router
->getContext();
293 //Force clean context
294 //XXX: prevent MethodNotAllowedException because current context method is POST in onevendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php+42
295 $this->router
->setContext(new RequestContext());
297 //Retrieve route matching path
298 $route = $this->router
->match($path);
301 $this->router
->setContext($oldContext);
307 $name = $route['_route'];
309 //Remove route and controller from route defaults
310 unset($route['_route'], $route['_controller']);
312 //Check if snippet view route
313 if ($name == 'rapsys_air_user_view' && !empty($route['id'])) {
315 $route['id'] = $snippet->getUser()->getId();
319 $route['snippet'] = $snippet->getId();
323 return $this->redirectToRoute($name, $route);
325 } catch(MethodNotAllowedException
|ResourceNotFoundException
$e) {
326 //Unset referer to fallback to default route
331 //Redirect to cleanup the form
332 return $this->redirectToRoute('rapsys_air', ['snippet' => $snippet->getId()]);