]> Raphaël G. Git Repositories - airbundle/blob - Controller/SessionController.php
Replace map getMap by image getMap function call
[airbundle] / Controller / SessionController.php
1 <?php declare(strict_types=1);
2
3 /*
4 * This file is part of the Rapsys AirBundle 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\AirBundle\Controller;
13
14 use Symfony\Component\Asset\Packages;
15 use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
16 use Symfony\Component\Filesystem\Filesystem;
17 use Symfony\Component\HttpFoundation\BinaryFileResponse;
18 use Symfony\Component\HttpFoundation\Request;
19 use Symfony\Component\HttpFoundation\Response;
20 use Symfony\Component\Routing\Exception\MethodNotAllowedException;
21 use Symfony\Component\Routing\Exception\ResourceNotFoundException;
22 use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
23 use Symfony\Component\Routing\RequestContext;
24
25 use Rapsys\AirBundle\Entity\Application;
26 use Rapsys\AirBundle\Entity\Dance;
27 use Rapsys\AirBundle\Entity\User;
28 use Rapsys\AirBundle\Entity\Slot;
29 use Rapsys\AirBundle\Entity\Session;
30 use Rapsys\AirBundle\Entity\Location;
31
32 class SessionController extends AbstractController {
33 /**
34 * List all sessions
35 *
36 * Display all sessions with an application or login form
37 *
38 * @param Request $request The request instance
39 *
40 * @return Response The rendered view
41 */
42 public function index(Request $request): Response {
43 //Get locations
44 $this->context['locations'] = $this->doctrine->getRepository(Location::class)->findAllAsArray($this->period);
45
46 //Add cities
47 $this->context['cities'] = $this->doctrine->getRepository(Location::class)->findCitiesAsArray($this->period);
48
49 //Add calendar
50 $this->context['calendar'] = $this->doctrine->getRepository(Session::class)->findAllByPeriodAsCalendarArray($this->period, !$this->checker->isGranted('IS_AUTHENTICATED_REMEMBERED'), null, null, 1);
51
52 //Add dances
53 $this->context['dances'] = $this->doctrine->getRepository(Dance::class)->findNamesAsArray();
54
55 //Set modified
56 $this->modified = max(array_map(function ($v) { return $v['modified']; }, array_merge($this->context['calendar'], $this->context['cities'], $this->context['dances'])));
57
58 //Create response
59 $response = new Response();
60
61 //With logged user
62 if ($this->checker->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
63 //Set last modified
64 $response->setLastModified(new \DateTime('-1 year'));
65
66 //Set as private
67 $response->setPrivate();
68 //Without logged user
69 } else {
70 //Set etag
71 //XXX: only for public to force revalidation by last modified
72 $response->setEtag(md5(serialize(array_merge($this->context['calendar'], $this->context['cities'], $this->context['dances']))));
73
74 //Set last modified
75 $response->setLastModified($this->modified);
76
77 //Set as public
78 $response->setPublic();
79
80 //Without role and modification
81 if ($response->isNotModified($request)) {
82 //Return 304 response
83 return $response;
84 }
85 }
86
87 //With cities
88 if (!empty($this->context['cities'])) {
89 //Set locations
90 $locations = [];
91
92 //Iterate on each cities
93 foreach($this->context['cities'] as $city) {
94 //Iterate on each locations
95 foreach($city['locations'] as $location) {
96 //Add location
97 $locations[$location['id']] = $location;
98 }
99 }
100
101 //Add multi
102 $this->context['multimap'] = $this->map->getMultiMap($this->translator->trans('Libre Air cities sector map'), $this->modified->getTimestamp(), $locations);
103
104 //Set cities
105 $cities = array_map(function ($v) { return $v['in']; }, $this->context['cities']);
106
107 //Set dances
108 $dances = array_map(function ($v) { return $v['name']; }, $this->context['dances']);
109 } else {
110 //Set cities
111 $cities = [];
112
113 //Set dances
114 $dances = [];
115 }
116
117 //Set keywords
118 //TODO: use splice instead of that shit !!!
119 //TODO: handle smartly indoor and outdoor !!!
120 $this->context['keywords'] = array_values(
121 array_merge(
122 $dances,
123 $cities,
124 [
125 $this->translator->trans('indoor'),
126 $this->translator->trans('outdoor'),
127 $this->translator->trans('sessions'),
128 $this->translator->trans('session list'),
129 $this->translator->trans('listing'),
130 $this->translator->trans('Libre Air')
131 ]
132 )
133 );
134
135 //Get textual cities
136 $cities = implode($this->translator->trans(' and '), array_filter(array_merge([implode(', ', array_slice($cities, 0, -1))], array_slice($cities, -1)), 'strlen'));
137
138 //Get textual dances
139 $dances = implode($this->translator->trans(' and '), array_filter(array_merge([implode(', ', array_slice($dances, 0, -1))], array_slice($dances, -1)), 'strlen'));
140
141 //Set title
142 $this->context['title']['page'] = $this->translator->trans('%dances% %cities% sessions', ['%dances%' => $dances, '%cities%' => $cities]);
143
144 //Set description
145 $this->context['description'] = $this->translator->trans('%dances% indoor and outdoor session calendar %cities%', ['%dances%' => $dances, '%cities%' => $cities]);
146
147 //Render the view
148 return $this->render('@RapsysAir/session/index.html.twig', $this->context);
149 }
150
151 /**
152 * List all sessions for tango argentin
153 *
154 * Display all sessions in tango argentin json format
155 *
156 * @todo Drop it if unused by tangoargentin ???
157 *
158 * @param Request $request The request instance
159 *
160 * @return Response The rendered view or redirection
161 */
162 public function tangoargentin(Request $request): Response {
163 //Retrieve events to update
164 $sessions = $this->doctrine->getRepository(Session::class)->findAllByPeriodAsCalendarArray($this->period);
165
166 //Init return array
167 $ret = [];
168
169 //Flatten sessions tree
170 $sessions = array_reduce($sessions, function ($c, $v) { return array_merge($c, $v['sessions']); }, []);
171
172 //Iterate on sessions
173 foreach($sessions as $sessionId => $session) {
174 //Set route params
175 $routeParams = $this->router->match($session['link']);
176
177 //Set route
178 $route = $routeParams['_route'];
179
180 //Drop _route from route params
181 unset($routeParams['_route']);
182
183 //Add session
184 $ret[$session['id']] = [
185 'start' => $session['start']->format(\DateTime::ISO8601),
186 'stop' => $session['start']->format(\DateTime::ISO8601),
187 'fromto' => $this->translator->trans('from %start% to %stop%', ['%start%' => $session['start']->format('H\hi'), '%stop%' => $session['stop']->format('H\hi')]),
188 'title' => $this->slugger->latin($session['application']['user']['title'])/*.' '.$this->translator->trans('at '.$session['location']['title'])*/,
189 'short' => $session['rate']['short'],
190 'rate' => $session['rate']['title'],
191 'location' => implode(' ', [$session['location']['address'], $session['location']['zipcode'], $session['location']['city']]),
192 'status' => in_array('canceled', $session['class'])?'annulé':'confirmé',
193 'modified' => $session['modified']->format(\DateTime::ISO8601),
194 #'organizer' => $session['application']['user']['title'],
195 #'source' => $this->router->generate('rapsysair_session_view', ['id' => $sessionId, 'location' => $this->translator->trans($session['l_title'])], UrlGeneratorInterface::ABSOLUTE_URL)
196 'source' => $this->router->generate($route, $routeParams, UrlGeneratorInterface::ABSOLUTE_URL)
197 ];
198 }
199
200 //Set response
201 $response = new Response(json_encode($ret));
202
203 //Set header
204 $response->headers->set('Content-Type', 'application/json');
205
206 //Send response
207 return $response;
208 }
209
210 /**
211 * Display session
212 *
213 * @todo XXX: TODO: add <link rel="prev|next" for sessions or classes ? />
214 * @todo XXX: TODO: like described in: https://www.alsacreations.com/article/lire/1400-attribut-rel-relations.html#xnf-rel-attribute
215 * @todo XXX: TODO: or here: http://microformats.org/wiki/existing-rel-values#HTML5_link_type_extensions
216 *
217 * @todo: generate a background from @RapsysAir/Resources/public/location/<location>.png or @RapsysAir/Resources/public/location/<user>/<location>.png when available
218 *
219 * @todo: generate a share picture @RapsysAir/seance/363/place-saint-sulpice/bal-et-cours-de-tango-argentin/milonga-raphael/share.jpeg ?
220 * (with date, organiser, type, location, times and logo ?)
221 *
222 * @todo: add picture stuff about location ???
223 *
224 * @param Request $request The request instance
225 * @param int $id The session id
226 *
227 * @return Response The rendered view
228 *
229 * @throws NotFoundHttpException When session is not found
230 */
231 public function view(Request $request, int $id): Response {
232 //Fetch session
233 if (empty($this->context['session'] = $this->doctrine->getRepository(Session::class)->findOneByIdAsArray($id))) {
234 //Session not found
235 throw $this->createNotFoundException($this->translator->trans('Unable to find session: %id%', ['%id%' => $id]));
236 }
237
238 //Get locations at less than 1 km
239 $this->context['locations'] = $this->doctrine->getRepository(Location::class)->findAllByLatitudeLongitudeAsArray($this->context['session']['location']['latitude'], $this->context['session']['location']['longitude'], $this->period, 2);
240
241 //Set modified
242 //XXX: dance modified is already computed inside calendar modified
243 $this->modified = max(array_merge([$this->context['session']['modified']], array_map(function ($v) { return $v['modified']; }, $this->context['locations'])));
244
245 //Create response
246 $response = new Response();
247
248 //With logged user
249 if ($this->checker->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
250 //Set last modified
251 $response->setLastModified(new \DateTime('-1 year'));
252
253 //Set as private
254 $response->setPrivate();
255 //Without logged user
256 } else {
257 //Set etag
258 //XXX: only for public to force revalidation by last modified
259 $response->setEtag(md5(serialize(array_merge($this->context['session'], $this->context['locations']))));
260
261 //Set last modified
262 $response->setLastModified($this->modified);
263
264 //Set as public
265 $response->setPublic();
266
267 //Without role and modification
268 if ($response->isNotModified($request)) {
269 //Return 304 response
270 return $response;
271 }
272 }
273
274 //Get route
275 $route = $request->attributes->get('_route');
276
277 //Get route params
278 $routeParams = $request->attributes->get('_route_params');
279
280 //Disable redirect
281 $redirect = false;
282
283 //Without location or invalid location
284 if (empty($routeParams['location']) || $this->context['session']['location']['slug'] !== $routeParams['location']) {
285 //Set location
286 $routeParams['location'] = $this->context['session']['location']['slug'];
287
288 //Enable redirect
289 $redirect = true;
290 }
291
292 //With dance slug without dance or invalid dance
293 if (!empty($this->context['session']['application']['dance']['slug']) && (empty($routeParams['dance']) || $this->context['session']['application']['dance']['slug'] !== $routeParams['dance'])) {
294 //Set dance
295 $routeParams['dance'] = $this->context['session']['application']['dance']['slug'];
296
297 //Enable redirect
298 $redirect = true;
299 //Without dance slug with dance
300 } elseif (empty($this->context['session']['application']['dance']['slug']) && !empty($routeParams['dance'])) {
301 //Set dance
302 unset($routeParams['dance']);
303
304 //Enable redirect
305 $redirect = true;
306 }
307
308 //With user slug without user or invalid user
309 if (!empty($this->context['session']['application']['user']['slug']) && (empty($routeParams['user']) || $this->context['session']['application']['user']['slug'] !== $routeParams['user'])) {
310 //Set user
311 $routeParams['user'] = $this->context['session']['application']['user']['slug'];
312
313 //Enable redirect
314 $redirect = true;
315 //Without user slug with user
316 } elseif (empty($this->context['session']['application']['user']['slug']) && !empty($routeParams['user'])) {
317 //Set user
318 unset($routeParams['user']);
319
320 //Enable redirect
321 $redirect = true;
322 }
323
324 //With redirect
325 if ($redirect) {
326 //Redirect to route
327 return $this->redirectToRoute($route, $routeParams, $this->context['session']['stop'] <= new \DateTime('now') ? Response::HTTP_MOVED_PERMANENTLY : Response::HTTP_FOUND);
328 }
329
330 //Add map
331 #$this->context['map'] = $this->map->getMap($this->context['session']['location']['map'], $this->modified->getTimestamp(), $this->context['session']['location']['latitude'], $this->context['session']['location']['longitude']);
332 $this->context['map'] = $this->image->getMap($this->context['session']['location']['latitude'], $this->context['session']['location']['longitude']) + ['caption' => $this->context['session']['location']['map']];
333
334 //Set coordinates
335 $coordinates = [];
336
337 //Iterate on each locations
338 foreach($this->context['locations'] as $location) {
339 //Add coordinates
340 $coordinates[] = [ $location['latitude'], $location['longitude'] ];
341 }
342
343 //Add multi map
344 #$this->context['multimap'] = $this->map->getMultiMap($this->context['session']['location']['multimap'], $this->modified->getTimestamp(), $this->context['locations']);
345 $this->context['multimap'] = $this->image->getMulti($coordinates) + ['caption' => $this->context['session']['location']['multimap']];
346
347 //Set canonical
348 $this->context['canonical'] = $this->context['session']['canonical'];
349
350 //Set alternates
351 $this->context['alternates'] = $this->context['session']['alternates'];
352
353 //Set localization date formater
354 $intlDate = new \IntlDateFormatter($this->locale, \IntlDateFormatter::TRADITIONAL, \IntlDateFormatter::NONE);
355
356 //Set localization time formater
357 $intlTime = new \IntlDateFormatter($this->locale, \IntlDateFormatter::NONE, \IntlDateFormatter::SHORT);
358
359 //With application
360 if (!empty($this->context['session']['application'])) {
361 //Set title
362 $this->context['title']['page'] = $this->translator->trans('%dance% %id% by %pseudonym%', ['%id%' => $id, '%dance%' => $this->context['session']['application']['dance']['title'], '%pseudonym%' => $this->context['session']['application']['user']['title']]);
363
364 //Set description
365 $this->context['description'] = ucfirst($this->translator->trans('%dance% %location% %city% %slot% on %date% at %time%', [
366 '%dance%' => $this->context['session']['application']['dance']['title'],
367 '%location%' => $this->context['session']['location']['at'],
368 '%city%' => $this->context['session']['location']['in'],
369 '%slot%' => $this->context['session']['slot']['the'],
370 '%date%' => $intlDate->format($this->context['session']['start']),
371 '%time%' => $intlTime->format($this->context['session']['start']),
372 ]));
373
374 //Set keywords
375 //TODO: readd outdoor ???
376 $this->context['keywords'] = [
377 $this->context['session']['application']['dance']['type'],
378 $this->context['session']['application']['dance']['name'],
379 $this->context['session']['location']['title'],
380 $this->context['session']['application']['user']['title'],
381 $this->translator->trans($this->context['session']['location']['indoor']?'indoor':'outdoor')
382 ];
383 //Without application
384 } else {
385 //Set title
386 $this->context['title']['page'] = $this->translator->trans('Session %id%', ['%id%' => $id]);
387
388 //Set description
389 $this->context['description'] = ucfirst($this->translator->trans('%location% %city% %slot% on %date% at %time%', [
390 '%city%' => ucfirst($this->context['session']['location']['in']),
391 '%location%' => $this->context['session']['location']['at'],
392 '%slot%' => $this->context['session']['slot']['the'],
393 '%date%' => $intlDate->format($this->context['session']['start']),
394 '%time%' => $intlTime->format($this->context['session']['start'])
395 ]));
396
397 //Add dance type
398 //TODO: readd outdoor ???
399 $this->context['keywords'] = [
400 $this->context['session']['location']['title'],
401 $this->translator->trans($this->context['session']['location']['indoor']?'indoor':'outdoor')
402 ];
403 }
404
405 //Set section
406 $this->context['section'] = $this->context['session']['location']['title'];
407
408 //Set facebook title
409 $this->context['facebook']['og:title'] = $this->context['title']['page'].' '.$this->context['session']['location']['at'];
410
411 //Set facebook image
412 $this->context['fbimage'] = [
413 'texts' => [
414 $this->context['session']['application']['user']['title']??$this->context['title']['page'] => [
415 'font' => 'irishgrover',
416 'size' => 110
417 ],
418 ucfirst($intlDate->format($this->context['session']['start']))."\n".$this->translator->trans('Around %start% until %stop%', ['%start%' => $intlTime->format($this->context['session']['start']), '%stop%' => $intlTime->format($this->context['session']['stop'])]) => [
419 'font' => 'irishgrover',
420 'align' => 'left'
421 ],
422 $this->context['session']['location']['at'] => [
423 'align' => 'right',
424 'font' => 'irishgrover',
425 'size' => 75
426 ]
427 ],
428 'updated' => $this->context['session']['updated']->format('U')
429 ]+$this->context['facebook'];
430
431 //Create application form for role_guest
432 if ($this->checker->isGranted('ROLE_GUEST')) {
433 //Set now
434 $now = new \DateTime('now');
435
436 //Default favorites and dances
437 $danceFavorites = $dances = [];
438 //Default dance
439 $danceDefault = null;
440
441 //With admin
442 if ($this->checker->isGranted('ROLE_ADMIN')) {
443 //Get favorites dances
444 $danceFavorites = $this->doctrine->getRepository(Dance::class)->findByUserId($this->security->getUser()->getId());
445
446 //Get dances
447 $dances = $this->doctrine->getRepository(Dance::class)->findAllIndexed();
448
449 //Set dance default
450 $danceDefault = !empty($this->context['session']['application'])?$dances[$this->context['session']['application']['dance']['id']]:null;
451 }
452
453 //Create SessionType form
454 //TODO: move to named form ???
455 $sessionForm = $this->factory->create('Rapsys\AirBundle\Form\SessionType', null, [
456 //Set the action
457 'action' => $this->generateUrl('rapsysair_session_view', ['id' => $id, 'location' => $this->context['session']['location']['slug'], 'dance' => $this->context['session']['application']['dance']['slug']??null, 'user' => $this->context['session']['application']['user']['slug']??null]),
458 //Set the form attribute
459 'attr' => [ 'class' => 'col' ],
460 //Set admin
461 'admin' => $this->checker->isGranted('ROLE_ADMIN'),
462 //Set dance choices
463 'dance_choices' => $dances,
464 //Set dance default
465 'dance_default' => $danceDefault,
466 //Set dance favorites
467 'dance_favorites' => $danceFavorites,
468 //Set to session slot or evening by default
469 //XXX: default to Evening (3)
470 'slot_default' => $this->doctrine->getRepository(Slot::class)->findOneById($this->context['session']['slot']['id']??3),
471 //Set default user to current
472 'user' => $this->security->getUser()->getId(),
473 //Set date
474 'date' => $this->context['session']['date'],
475 //Set begin
476 'begin' => $this->context['session']['begin'],
477 //Set length
478 'length' => $this->context['session']['length'],
479 //Set raincancel
480 'raincancel' => ($this->checker->isGranted('ROLE_ADMIN') || !empty($this->context['session']['application']['user']['id']) && $this->security->getUser()->getId() == $this->context['session']['application']['user']['id']) && $this->context['session']['rainfall'] >= 2,
481 //Set cancel
482 'cancel' => $this->checker->isGranted('ROLE_ADMIN') || in_array($this->security->getUser()->getId(), explode("\n", $this->context['session']['sau_id'])),
483 //Set modify
484 'modify' => $this->checker->isGranted('ROLE_ADMIN') || !empty($this->context['session']['application']['user']['id']) && $this->security->getUser()->getId() == $this->context['session']['application']['user']['id'] && $this->context['session']['stop'] >= $now && $this->checker->isGranted('ROLE_REGULAR'),
485 //Set move
486 'move' => $this->checker->isGranted('ROLE_ADMIN') || !empty($this->context['session']['application']['user']['id']) && $this->security->getUser()->getId() == $this->context['session']['application']['user']['id'] && $this->context['session']['stop'] >= $now && $this->checker->isGranted('ROLE_SENIOR'),
487 //Set attribute
488 'attribute' => $this->checker->isGranted('ROLE_ADMIN') && $this->context['session']['locked'] === null,
489 //Set session
490 'session' => $this->context['session']['id']
491 ]);
492
493 //Refill the fields in case of invalid form
494 $sessionForm->handleRequest($request);
495
496 //With submitted form
497 if ($sessionForm->isSubmitted() && $sessionForm->isValid()) {
498 //Get data
499 $data = $sessionForm->getData();
500
501 //Fetch session
502 $sessionObject = $this->doctrine->getRepository(Session::class)->findOneById($id);
503
504 //Set user
505 $userObject = $this->security->getUser();
506
507 //Replace with requested user for admin
508 if ($this->checker->isGranted('ROLE_ADMIN') && !empty($data['user'])) {
509 $userObject = $this->doctrine->getRepository(User::class)->findOneById($data['user']);
510 }
511
512 //Set datetime
513 $datetime = new \DateTime('now');
514
515 //Set canceled time at start minus one day
516 $canceled = (clone $sessionObject->getStart())->sub(new \DateInterval('P1D'));
517
518 //Set action
519 $action = [
520 'raincancel' => $sessionForm->has('raincancel') && $sessionForm->get('raincancel')->isClicked(),
521 'modify' => $sessionForm->has('modify') && $sessionForm->get('modify')->isClicked(),
522 'move' => $sessionForm->has('move') && $sessionForm->get('move')->isClicked(),
523 'cancel' => $sessionForm->has('cancel') && $sessionForm->get('cancel')->isClicked(),
524 'forcecancel' => $sessionForm->has('forcecancel') && $sessionForm->get('forcecancel')->isClicked(),
525 'attribute' => $sessionForm->has('attribute') && $sessionForm->get('attribute')->isClicked(),
526 'autoattribute' => $sessionForm->has('autoattribute') && $sessionForm->get('autoattribute')->isClicked(),
527 'lock' => $sessionForm->has('lock') && $sessionForm->get('lock')->isClicked(),
528 ];
529
530 //With raincancel and application and (rainfall or admin)
531 if ($action['raincancel'] && ($application = $sessionObject->getApplication()) && ($sessionObject->getRainfall() >= 2 || $this->checker->isGranted('ROLE_ADMIN'))) {
532 //Cancel application at start minus one day
533 $application->setCanceled($canceled);
534
535 //Update time
536 $application->setUpdated($datetime);
537
538 //Insufficient rainfall
539 //XXX: is admin
540 if ($sessionObject->getRainfall() < 2) {
541 //Set score
542 //XXX: magic cheat score 42
543 $application->setScore(42);
544 }
545
546 //Queue application save
547 $this->manager->persist($application);
548
549 //Add notice in flash message
550 $this->addFlash('notice', $this->translator->trans('Application %id% updated', ['%id%' => $application->getId()]));
551
552 //Update time
553 $sessionObject->setUpdated($datetime);
554
555 //Queue session save
556 $this->manager->persist($sessionObject);
557
558 //Add notice in flash message
559 $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id]));
560 //With modify
561 } elseif ($action['modify']) {
562 //With admin
563 if ($this->checker->isGranted('ROLE_ADMIN')) {
564 //Get application
565 $application = $this->doctrine->getRepository(Application::class)->findOneBySessionUser($sessionObject, $userObject);
566
567 //Set dance
568 $application->setDance($data['dance']);
569
570 //Queue session save
571 $this->manager->persist($application);
572
573 //Set slot
574 $sessionObject->setSlot($data['slot']);
575
576 //Set date
577 $sessionObject->setDate($data['date']);
578 }
579
580 //Set begin
581 $sessionObject->setBegin($data['begin']);
582
583 //Set length
584 $sessionObject->setLength($data['length']);
585
586 //Update time
587 $sessionObject->setUpdated($datetime);
588
589 //Queue session save
590 $this->manager->persist($sessionObject);
591
592 //Add notice in flash message
593 $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id]));
594 //With move
595 } elseif ($action['move']) {
596 //Set location
597 $sessionObject->setLocation($this->doctrine->getRepository(Location::class)->findOneById($data['location']));
598
599 //Update time
600 $sessionObject->setUpdated($datetime);
601
602 //Queue session save
603 $this->manager->persist($sessionObject);
604
605 //Add notice in flash message
606 $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id]));
607 //With cancel or forcecancel
608 } elseif ($action['cancel'] || $action['forcecancel']) {
609 //Get application
610 $application = $this->doctrine->getRepository(Application::class)->findOneBySessionUser($sessionObject, $userObject);
611
612 //Not already canceled
613 if ($application->getCanceled() === null) {
614 //Cancel application
615 $application->setCanceled($datetime);
616
617 //Check if application is session application and (canceled 24h before start or forcecancel (as admin))
618 #if ($sessionObject->getApplication() == $application && ($datetime < $canceled || $action['forcecancel'])) {
619 if ($sessionObject->getApplication() == $application && $action['forcecancel']) {
620 //Set score
621 //XXX: magic cheat score 42
622 $application->setScore(42);
623
624 //Unattribute session
625 $sessionObject->setApplication(null);
626
627 //Update time
628 $sessionObject->setUpdated($datetime);
629
630 //Queue session save
631 $this->manager->persist($sessionObject);
632
633 //Add notice in flash message
634 $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id]));
635 }
636 //Already canceled
637 } else {
638 //Uncancel application
639 $application->setCanceled(null);
640 }
641
642 //Update time
643 $application->setUpdated($datetime);
644
645 //Queue application save
646 $this->manager->persist($application);
647
648 //Add notice in flash message
649 $this->addFlash('notice', $this->translator->trans('Application %id% updated', ['%id%' => $application->getId()]));
650 //With attribute
651 } elseif ($action['attribute']) {
652 //Get application
653 $application = $this->doctrine->getRepository(Application::class)->findOneBySessionUser($sessionObject, $userObject);
654
655 //Already canceled
656 if ($application->getCanceled() !== null) {
657 //Uncancel application
658 $application->setCanceled(null);
659 }
660
661 //Set score
662 //XXX: magic cheat score 42
663 $application->setScore(42);
664
665 //Update time
666 $application->setUpdated($datetime);
667
668 //Queue application save
669 $this->manager->persist($application);
670
671 //Add notice in flash message
672 $this->addFlash('notice', $this->translator->trans('Application %id% updated', ['%id%' => $application->getId()]));
673
674 //Unattribute session
675 $sessionObject->setApplication($application);
676
677 //Update time
678 $sessionObject->setUpdated($datetime);
679
680 //Queue session save
681 $this->manager->persist($sessionObject);
682
683 //Add notice in flash message
684 $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id]));
685 //With autoattribute
686 } elseif ($action['autoattribute']) {
687 //Get best application
688 //XXX: best application may not issue result while grace time or bad behaviour
689 if (!empty($application = $this->doctrine->getRepository(Session::class)->findBestApplicationById($id))) {
690 //Attribute session
691 $sessionObject->setApplication($application);
692
693 //Update time
694 $sessionObject->setUpdated($datetime);
695
696 //Queue session save
697 $this->manager->persist($sessionObject);
698
699 //Add notice in flash message
700 $this->addFlash('notice', $this->translator->trans('Session %id% auto attributed', ['%id%' => $id]));
701 //No application
702 } else {
703 //Add warning in flash message
704 $this->addFlash('warning', $this->translator->trans('Session %id% not auto attributed', ['%id%' => $id]));
705 }
706 //With lock
707 } elseif ($action['lock']) {
708 //Already locked
709 if ($sessionObject->getLocked() !== null) {
710 //Set uncanceled
711 $canceled = null;
712
713 //Unlock session
714 $sessionObject->setLocked(null);
715 //Not locked
716 } else {
717 //Get application
718 if ($application = $sessionObject->getApplication()) {
719 //Set score
720 //XXX: magic cheat score 42
721 $application->setScore(42);
722
723 //Update time
724 $application->setUpdated($datetime);
725
726 //Queue application save
727 $this->manager->persist($application);
728
729 //Add notice in flash message
730 $this->addFlash('notice', $this->translator->trans('Application %id% updated', ['%id%' => $application->getId()]));
731 }
732
733 //Unattribute session
734 $sessionObject->setApplication(null);
735
736 //Lock session
737 $sessionObject->setLocked($datetime);
738 }
739
740 //Update time
741 $sessionObject->setUpdated($datetime);
742
743 //Queue session save
744 $this->manager->persist($sessionObject);
745
746 //Add notice in flash message
747 $this->addFlash('notice', $this->translator->trans('Session %id% updated', ['%id%' => $id]));
748 //Unknown action
749 } else {
750 //Add warning in flash message
751 $this->addFlash('warning', $this->translator->trans('Session %id% not updated', ['%id%' => $id]));
752 }
753
754 //Flush to get the ids
755 $this->manager->flush();
756
757 //Redirect to cleanup the form
758 return $this->redirectToRoute('rapsysair_session_view', ['id' => $id, 'location' => $this->context['session']['location']['slug'], 'dance' => $this->context['session']['application']['dance']['slug']??null, 'user' => $this->context['session']['application']['user']['slug']??null]);
759 }
760
761 //Add form to context
762 $this->context['forms']['session'] = $sessionForm->createView();
763 }
764
765 //Render the view
766 return $this->render('@RapsysAir/session/view.html.twig', $this->context, $response);
767 }
768 }