Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
10.31% covered (danger)
10.31%
33 / 320
21.74% covered (danger)
21.74%
5 / 23
CRAP
0.00% covered (danger)
0.00%
0 / 1
SurveyController
10.31% covered (danger)
10.31%
33 / 320
21.74% covered (danger)
21.74%
5 / 23
7460.33
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 getDomain
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getModel
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getModelClass
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getFormType
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getListData
84.62% covered (warning)
84.62%
11 / 13
0.00% covered (danger)
0.00%
0 / 1
3.03
 formPrePersistData
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 createMaturitySurveyAction
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
42
 editAction
0.00% covered (danger)
0.00%
0 / 49
0.00% covered (danger)
0.00%
0 / 1
272
 reportAction
72.73% covered (warning)
72.73%
8 / 11
0.00% covered (danger)
0.00%
0 / 1
7.99
 startSurveyAction
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 referentielsDatatablesAction
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
30
 getBaseReferentielsDataTablesResponse
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 getReferentielResults
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
 getCorrespondingLabelFromkeyForReferentiels
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 getLabelAndKeysArrayForReferentiels
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 listAction
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
20
 listDataTables
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
20
 generateActionCellContent
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
6
 getLabelAndKeysArray
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
6
 syntheseAction
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
240
 deleteAction
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
132
 deleteConfirmationAction
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
90
1<?php
2
3/**
4 * This file is part of the MADIS - RGPD Management application.
5 *
6 * @copyright Copyright (c) 2018-2019 Soluris - Solutions Numériques Territoriales Innovantes
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU Affero General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU Affero General Public License for more details.
17 *
18 * You should have received a copy of the GNU Affero General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22declare(strict_types=1);
23
24namespace App\Domain\Maturity\Controller;
25
26use App\Application\Controller\CRUDController;
27use App\Application\Interfaces\CollectivityRelated;
28use App\Application\Symfony\Security\UserProvider;
29use App\Application\Traits\ServersideDatatablesTrait;
30use App\Domain\Documentation\Model\Category;
31use App\Domain\Maturity\Calculator\MaturityHandler;
32use App\Domain\Maturity\Form\Type\SurveyType;
33use App\Domain\Maturity\Form\Type\SyntheseType;
34use App\Domain\Maturity\Model;
35use App\Domain\Maturity\Repository;
36use App\Domain\Reporting\Handler\WordHandler;
37use App\Domain\User\Dictionary\UserRoleDictionary;
38use App\Domain\User\Model\Collectivity;
39use App\Domain\User\Model\User;
40use Doctrine\ORM\EntityManagerInterface;
41use Doctrine\ORM\Tools\Pagination\Paginator;
42use Knp\Snappy\Pdf;
43use Symfony\Component\HttpFoundation\JsonResponse;
44use Symfony\Component\HttpFoundation\Request;
45use Symfony\Component\HttpFoundation\RequestStack;
46use Symfony\Component\HttpFoundation\Response;
47use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
48use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
49use Symfony\Component\Routing\RouterInterface;
50use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
51use Symfony\Component\Security\Core\Security;
52use Symfony\Contracts\Translation\TranslatorInterface;
53use Symfony\Polyfill\Intl\Icu\Exception\MethodNotImplementedException;
54
55/**
56 * @property Repository\Survey $repository
57 */
58class SurveyController extends CRUDController
59{
60    use ServersideDatatablesTrait;
61
62    /**
63     * @var WordHandler
64     */
65    private $wordHandler;
66
67    /**
68     * @var AuthorizationCheckerInterface
69     */
70    protected $authorizationChecker;
71
72    /**
73     * @var UserProvider
74     */
75    protected $userProvider;
76
77    /**
78     * @var MaturityHandler
79     */
80    protected $maturityHandler;
81
82    protected Repository\Question $questionRepository;
83
84    private Repository\Referentiel $referentielRepository;
85    private $router;
86    private RequestStack $requestStack;
87    private Security $security;
88
89    public function __construct(
90        EntityManagerInterface $entityManager,
91        TranslatorInterface $translator,
92        Repository\Survey $repository,
93        Repository\Question $questionRepository,
94        WordHandler $wordHandler,
95        AuthorizationCheckerInterface $authorizationChecker,
96        UserProvider $userProvider,
97        MaturityHandler $maturityHandler,
98        Pdf $pdf,
99        Repository\Referentiel $referentielRepository,
100        RouterInterface $router,
101        RequestStack $requestStack,
102        Security $security,
103    ) {
104        parent::__construct($entityManager, $translator, $repository, $pdf, $userProvider, $authorizationChecker);
105        $this->questionRepository    = $questionRepository;
106        $this->wordHandler           = $wordHandler;
107        $this->authorizationChecker  = $authorizationChecker;
108        $this->userProvider          = $userProvider;
109        $this->maturityHandler       = $maturityHandler;
110        $this->referentielRepository = $referentielRepository;
111        $this->router                = $router;
112        $this->requestStack          = $requestStack;
113        $this->security              = $security;
114    }
115
116    protected function getDomain(): string
117    {
118        return 'maturity';
119    }
120
121    protected function getModel(): string
122    {
123        return 'survey';
124    }
125
126    protected function getModelClass(): string
127    {
128        return Model\Survey::class;
129    }
130
131    protected function getFormType(): string
132    {
133        return SurveyType::class;
134    }
135
136    protected function getListData()
137    {
138        $order = [
139            'createdAt' => 'DESC',
140        ];
141
142        if ($this->authorizationChecker->isGranted('ROLE_ADMIN')) {
143            return $this->repository->findAll($order);
144        }
145
146        if ($this->authorizationChecker->isGranted('ROLE_REFERENT')) {
147            $collectivities = \iterable_to_array($this->userProvider->getAuthenticatedUser()->getCollectivitesReferees());
148
149            return $this->repository->findAllByCollectivities($collectivities, $order);
150        }
151
152        $data = $this->repository->findAllByCollectivity(
153            $this->userProvider->getAuthenticatedUser()->getCollectivity(),
154            $order
155        );
156
157        return $data;
158    }
159
160    /**
161     * {@inheritdoc}
162     * Here, we wanna compute maturity score.
163     *
164     * @param Model\Survey $object
165     */
166    public function formPrePersistData($object, $form = null)
167    {
168        // Removed because this is done in App\Domain\Maturity\Symfony\EventSubscriber\Doctrine\GenerateMaturitySubscriber
169        // $this->maturityHandler->handle($object);
170    }
171
172    /**
173     * {@inheritdoc}
174     * Override method in order to hydrate survey answers.
175     */
176    public function createMaturitySurveyAction(Request $request): Response
177    {
178        $object = new Model\Survey();
179
180        /** @var Model\Referentiel $referentiel */
181        $referentiel = $this->entityManager->getRepository(Model\Referentiel::class)->findOneBy([
182            'id' => $request->get('referentiel'),
183        ]);
184
185        $object->setReferentiel($referentiel);
186
187        $form = $this->createForm($this->getFormType(), $object);
188
189        $form->setData(['referentiel' => $request->get('referentiel')]);
190
191        $form->handleRequest($request);
192
193        $answerSurveys = [];
194
195        if ($form->isSubmitted()) {
196            $data = $request->request->all();
197            if (isset($data['survey']['questions'])) {
198                foreach ($data['survey']['questions'] as $questionId => $question) {
199                    if (isset($question['option'])) {
200                        // Create new OptionalAnswer
201                        $opa = new Model\OptionalAnswer();
202                        $q   = $this->entityManager->getRepository(Model\Question::class)->find($questionId);
203                        $opa->setQuestion($q);
204                        $this->entityManager->persist($opa);
205                        $object->addOptionalAnswer($opa);
206                    } else {
207                        foreach ($question['answers'] as $answerId) {
208                            $answer = $this->entityManager->getRepository(Model\Answer::class)->find($answerId);
209                            $as     = new Model\AnswerSurvey();
210                            $as->setSurvey($object);
211                            $as->setAnswer($answer);
212                            $answerSurveys[] = $as;
213                        }
214                    }
215                }
216            }
217            $object->setAnswerSurveys($answerSurveys);
218            $this->formPrePersistData($object);
219            $this->entityManager->persist($object);
220            $this->entityManager->flush();
221
222            $this->addFlash('success', $this->getFlashbagMessage('success', 'create', $object->__toString()));
223
224            return $this->redirectToRoute($this->getRouteName('synthesis'), ['id' => $object->getId()]);
225        }
226
227        return $this->render($this->getTemplatingBasePath('create'), [
228            'form' => $form->createView(),
229        ]);
230    }
231
232    /**
233     * {@inheritdoc}
234     * Override method in order to hydrate survey answers.
235     */
236    public function editAction(Request $request, string $id): Response
237    {
238        /**
239         * @var Model\Survey $object
240         */
241        $object = $this->repository->findOneById($id);
242        if (!$object) {
243            throw new NotFoundHttpException("No object found with ID '{$id}'");
244        }
245
246        if (
247            !$this->authorizationChecker->isGranted('ROLE_ADMIN')
248            && $this->userProvider->getAuthenticatedUser() !== $object->getCreator()
249            && $this->userProvider->getAuthenticatedUser()->getCollectivity() !== $object->getCollectivity()
250            && !($this->authorizationChecker->isGranted('ROLE_REFERENT') && !in_array($object->getCollectivity(), (array) $this->userProvider->getAuthenticatedUser()->getCollectivitesReferees()))
251        ) {
252            throw new NotFoundHttpException("No object found with ID '{$id}'");
253        }
254
255        $toDelete = $this->entityManager->getRepository(Model\AnswerSurvey::class)->findBy(['survey' => $object]);
256
257        $form = $this->createForm($this->getFormType(), $object);
258
259        $form->setData(['referentiel' => $request->get('referentiel')]);
260
261        $form->handleRequest($request);
262
263        if ($form->isSubmitted()) {
264            $data          = $request->request->all();
265            $answerSurveys = [];
266            if (isset($data['survey']['questions'])) {
267                foreach ($data['survey']['questions'] as $questionId => $question) {
268                    // Remove optional answer if one exists
269                    $q              = $this->entityManager->getRepository(Model\Question::class)->find($questionId);
270                    $optionalAnswer = $this->entityManager->getRepository(Model\OptionalAnswer::class)->findOneBy(['question' => $q, 'survey' => $object]);
271                    if ($optionalAnswer) {
272                        $this->entityManager->remove($optionalAnswer);
273                    }
274                    if (isset($question['option'])) {
275                        // Create new OptionalAnswer
276                        $opa = new Model\OptionalAnswer();
277
278                        $opa->setQuestion($q);
279                        $this->entityManager->persist($opa);
280                        $object->addOptionalAnswer($opa);
281                    } else {
282                        foreach ($question['answers'] as $answerId) {
283                            /** @var Model\Answer $answer */
284                            $answer = $this->entityManager->getRepository(Model\Answer::class)->find($answerId);
285                            $as     = $this->entityManager->getRepository(Model\AnswerSurvey::class)->findOneBy(['answer' => $answer, 'survey' => $object]);
286                            if (!$as) {
287                                $as = new Model\AnswerSurvey();
288                            }
289
290                            $as->setSurvey($object);
291                            $as->setAnswer($answer);
292                            $this->entityManager->persist($as);
293                            $answerSurveys[] = $as;
294
295                            $toDelete = array_filter($toDelete, function (Model\AnswerSurvey $asd) use ($as) {
296                                return !$as->getId() || $as->getId() !== $asd->getId();
297                            });
298                        }
299                    }
300                }
301            }
302
303            foreach ($toDelete as $asd) {
304                $this->entityManager->remove($asd);
305            }
306            $object->setAnswerSurveys($answerSurveys);
307            $this->formPrePersistData($object);
308            $this->entityManager->persist($object);
309            $this->entityManager->flush();
310
311            $this->addFlash('success', $this->getFlashbagMessage('success', 'edit', $object->__toString()));
312
313            return $this->redirectToRoute($this->getRouteName('synthesis'), ['id' => $object->getId()]);
314        }
315
316        return $this->render($this->getTemplatingBasePath('edit'), [
317            'form' => $form->createView(),
318        ]);
319    }
320
321    /**
322     * Generate a word report of survey.
323     * Get current survey and previous one.
324     *
325     * @throws \PhpOffice\PhpWord\Exception\Exception
326     */
327    public function reportAction(string $id): Response
328    {
329        $data        = [];
330        $data['new'] = $this->repository->findOneById($id);
331
332        if (
333            !$this->authorizationChecker->isGranted('ROLE_ADMIN')
334            && $this->userProvider->getAuthenticatedUser() !== $data['new']->getCreator()
335            && $this->userProvider->getAuthenticatedUser()->getCollectivity() !== $data['new']->getCollectivity()
336            && !($this->authorizationChecker->isGranted('ROLE_REFERENT') && !in_array($data['new']->getCollectivity(), (array) $this->userProvider->getAuthenticatedUser()->getCollectivitesReferees()))
337        ) {
338            throw new NotFoundHttpException("No object found with ID '{$id}'");
339        }
340
341        $oldObjects = $this->repository->findPreviousById($id, 1);
342        if (!empty($oldObjects)) {
343            $data['old'] = $oldObjects[0];
344        }
345
346        return $this->wordHandler->generateMaturitySurveyReport($data);
347    }
348
349    public function startSurveyAction(Request $request)
350    {
351        if ($request->isMethod('GET')) {
352            /** @var User $user */
353            $user = $this->getUser();
354
355            if (
356                !$this->authorizationChecker->isGranted('ROLE_USER')
357            ) {
358                throw new AccessDeniedHttpException('Vous n\'avez pas accès Ã  cette fonctionalité');
359            }
360
361            return $this->render($this->getTemplatingBasePath('start'), [
362                'totalItem' => $this->referentielRepository->count(),
363                'route'     => $this->router->generate('maturity_survey_referentiel_datatables', ['collectivity' => $user->getCollectivity()->getId()->toString()]),
364            ]);
365        }
366
367        if (null === $referentiel = $this->referentielRepository->findOneById($request->request->get('referentiel_choice'))) {
368            throw new NotFoundHttpException('No referentiel with Id ' . $request->request->get('referentiel_choice') . ' exists.');
369        }
370
371        return $this->redirectToRoute('maturity_survey_create', [
372            'referentiel' => $referentiel->getId(),
373        ]);
374    }
375
376    public function referentielsDatatablesAction()
377    {
378        $request      = $this->requestStack->getMasterRequest();
379        $referentiels = $this->getReferentielResults($request);
380
381        $collectivity = $this->entityManager->getRepository(Collectivity::class)->find($request->query->get('collectivity'));
382
383        $reponse = $this->getBaseReferentielsDataTablesResponse($request, $referentiels);
384
385        foreach ($referentiels as $referentiel) {
386            /** @var Model\Referentiel $collectivityType */
387            $collectivityType            = $collectivity->getType();
388            $authorizedCollectivities    = $referentiel->getAuthorizedCollectivities();
389            $authorizedCollectivityTypes = $referentiel->getAuthorizedCollectivityTypes();
390
391            if ((!\is_null($authorizedCollectivityTypes)
392                    && in_array($collectivityType, $authorizedCollectivityTypes))
393                || $authorizedCollectivities->contains($collectivity)
394            ) {
395                $reponse['data'][] = [
396                    'name'        => '<div class="radio"><label class="required" for="' . $referentiel->getId() . '"><input type="radio" id="' . $referentiel->getId() . '" value="' . $referentiel->getId() . '" name="referentiel_choice" required="true"/> ' . $referentiel->getName() . '</label></div>',
397                    'description' => $referentiel->getDescription(),
398                ];
399            }
400        }
401
402        $reponse['recordsTotal']    = count($reponse['data']);
403        $reponse['recordsFiltered'] = count($reponse['data']);
404
405        return new JsonResponse($reponse);
406    }
407
408    protected function getBaseReferentielsDataTablesResponse(Request $request, $results, array $criteria = [])
409    {
410        $draw = $request->request->get('draw');
411
412        $reponse = [
413            'draw'            => $draw,
414            'recordsTotal'    => $this->referentielRepository->count($criteria),
415            'recordsFiltered' => count($results),
416            'data'            => [],
417        ];
418
419        return $reponse;
420    }
421
422    protected function getReferentielResults(Request $request): ?Paginator
423    {
424        $first      = $request->request->get('start');
425        $maxResults = $request->request->get('length');
426        $orders     = $request->request->get('order');
427        $columns    = $request->request->get('columns');
428
429        $orderColumn = $this->getCorrespondingLabelFromkeyForReferentiels($orders[0]['column']);
430        $orderDir    = $orders[0]['dir'];
431
432        $searches = [];
433        foreach ($columns as $column) {
434            if ('' !== $column['search']['value']) {
435                $searches[$column['data']] = $column['search']['value'];
436            }
437        }
438
439        return $this->referentielRepository->findPaginated($first, $maxResults, $orderColumn, $orderDir, $searches);
440    }
441
442    private function getCorrespondingLabelFromkeyForReferentiels(string $key)
443    {
444        return \array_key_exists($key, $this->getLabelAndKeysArrayForReferentiels()) ? $this->getLabelAndKeysArrayForReferentiels()[$key] : null;
445    }
446
447    private function getLabelAndKeysArrayForReferentiels()
448    {
449        return [
450            '0' => 'name',
451            '1' => 'description',
452        ];
453    }
454
455    public function listAction(): Response
456    {
457        $surveys      = $this->getListData();
458        $referentiels = [];
459        foreach ($surveys as $survey) {
460            $referentiels[] = $survey->getReferentiel()->getName();
461        }
462        $user     = $this->userProvider->getAuthenticatedUser();
463        $criteria = [];
464        if (!$this->authorizationChecker->isGranted('ROLE_ADMIN')) {
465            $criteria['collectivity'] = $this->userProvider->getAuthenticatedUser()->getCollectivity();
466        }
467        if (\in_array(UserRoleDictionary::ROLE_REFERENT, $user->getRoles())) {
468            $criteria['collectivity'] = $user->getCollectivitesReferees();
469        }
470
471        $category = $this->entityManager->getRepository(Category::class)->findOneBy([
472            'name' => 'Indice de maturité',
473        ]);
474
475        return $this->render('Maturity/Survey/list.html.twig', [
476            'category'     => $category,
477            'totalItem'    => $this->repository->count($criteria),
478            'route'        => $this->router->generate('maturity_survey_list_datatables'),
479            'referentiels' => array_unique($referentiels, SORT_STRING),
480        ]);
481    }
482
483    public function listDataTables(Request $request): JsonResponse
484    {
485        $criteria = [];
486        $user     = $this->userProvider->getAuthenticatedUser();
487        if (!$this->authorizationChecker->isGranted('ROLE_ADMIN')) {
488            $criteria['collectivity'] = $this->userProvider->getAuthenticatedUser()->getCollectivity();
489        }
490        if (\in_array(UserRoleDictionary::ROLE_REFERENT, $user->getRoles())) {
491            $criteria['collectivity'] = $user->getCollectivitesReferees();
492        }
493        $surveys = $this->getResults($request, $criteria);
494        $reponse = $this->getBaseDataTablesResponse($request, $surveys);
495
496        foreach ($surveys as $survey) {
497            $referentielLink = '<a href="' . $this->router->generate('maturity_survey_synthesis', ['id' => $survey->getId()->toString()]) . '">
498                ' . \htmlspecialchars($survey->getReferentiel()->getName()) . '
499                </a>';
500
501            $reponse['data'][] = [
502                'collectivity' => $survey->getCollectivity()->getName(),
503                'referentiel'  => $referentielLink,
504                'score'        => $survey->getScore() / 10,
505                'createdAt'    => date_format($survey->getCreatedAt(), 'd-m-Y H:i'),
506                'updatedAt'    => date_format($survey->getUpdatedAt(), 'd-m-Y H:i'),
507                'actions'      => $this->generateActionCellContent($survey),
508            ];
509        }
510        $reponse['recordsTotal'] = $this->repository->count($criteria);
511
512        return new JsonResponse($reponse);
513    }
514
515    private function generateActionCellContent(Model\Survey $survey): string
516    {
517        $id = $survey->getId();
518
519        $content = '<a href="' . $this->router->generate('maturity_survey_report', ['id' => $id]) . '">
520                <i aria-hidden="true" class="fa fa-print"></i> '
521            . $this->translator->trans('global.action.print') .
522            '</a>' .
523            '<a href="' . $this->router->generate('maturity_survey_synthesis', ['id' => $id]) . '">
524                <i aria-hidden="true" class="fa fa-chart-line"></i> ' .
525            $this->translator->trans('global.action.synthesis') .
526            '</a>';
527        if ($this->security->isGranted('ROLE_USER')) {
528            $content .= '<a href="' . $this->router->generate('maturity_survey_edit', ['id' => $id]) . '">
529                <i aria-hidden="true" class="fa fa-pencil"></i> '
530            . $this->translator->trans('global.action.edit') .
531            '</a>' .
532            '<a href="' . $this->router->generate('maturity_survey_delete', ['id' => $id]) . '">
533                <i aria-hidden="true" class="fa fa-trash"></i> ' .
534            $this->translator->trans('global.action.delete') .
535            '</a>';
536        }
537
538        return $content;
539    }
540
541    protected function getLabelAndKeysArray(): array
542    {
543        if ($this->isGranted('ROLE_REFERENT')) {
544            return [
545                'referentiel',
546                'collectivity',
547                'score',
548                'createdAt',
549                'updatedAt',
550                'actions',
551            ];
552        }
553
554        return [
555            'referentiel',
556            'score',
557            'createdAt',
558            'updatedAt',
559            'actions',
560        ];
561    }
562
563    public function syntheseAction(Request $request, string $id): Response
564    {
565        //        /** @var CollectivityRelated $object */
566        $object = $this->repository->findOneById($id);
567        if (!$object) {
568            throw new NotFoundHttpException("No object found with ID '{$id}'");
569        }
570
571        if (
572            !$this->authorizationChecker->isGranted('ROLE_ADMIN')
573            && $this->userProvider->getAuthenticatedUser() !== $object->getCreator()
574            && $this->userProvider->getAuthenticatedUser()->getCollectivity() !== $object->getCollectivity()
575            && !($this->authorizationChecker->isGranted('ROLE_REFERENT') && !in_array($object->getCollectivity(), (array) $this->userProvider->getAuthenticatedUser()->getCollectivitesReferees()))
576        ) {
577            throw new NotFoundHttpException("No object found with ID '{$id}'");
578        }
579
580        $previous = $this->repository->findPreviousById($id);
581
582        $serviceEnabled = false;
583
584        if ($object instanceof Collectivity) {
585            $serviceEnabled = $object->getIsServicesEnabled();
586        } elseif ($object instanceof CollectivityRelated) {
587            $serviceEnabled = $object->getCollectivity()->getIsServicesEnabled();
588        }
589
590        /**
591         * @var User $user
592         */
593        $user = $this->getUser();
594
595        $actionEnabled = true;
596        if ($object instanceof CollectivityRelated && (!$this->authorizationChecker->isGranted('ROLE_ADMIN') && !$user->getServices()->isEmpty())) {
597            $actionEnabled = $object->isInUserServices($this->userProvider->getAuthenticatedUser());
598        }
599
600        if (!$actionEnabled) {
601            return $this->redirectToRoute($this->getRouteName('list'));
602        }
603
604        $form = $this->createForm(SyntheseType::class, $object);
605
606        $form->handleRequest($request);
607
608        if ($form->isSubmitted() && $form->isValid()) {
609            $this->entityManager->persist($object);
610            $this->entityManager->flush();
611
612            $this->addFlash('success', $this->getFlashbagMessage('success', 'edit', $object));
613
614            return $this->redirectToRoute($this->getRouteName('list'));
615        }
616
617        return $this->render($this->getTemplatingBasePath('synthese'), [
618            'form'     => $form->createView(),
619            'object'   => $object,
620            'previous' => $previous,
621        ]);
622    }
623
624    /**
625     * The delete action view
626     * Display a confirmation message to confirm data deletion.
627     */
628    public function deleteAction(string $id): Response
629    {
630        /** @var Model\Survey $object */
631        $object = $this->repository->findOneById($id);
632        if (!$object) {
633            throw new NotFoundHttpException("No object found with ID '{$id}'");
634        }
635
636        if (
637            !$this->authorizationChecker->isGranted('ROLE_ADMIN')
638            && $this->userProvider->getAuthenticatedUser() !== $object->getCreator()
639            && $this->userProvider->getAuthenticatedUser()->getCollectivity() !== $object->getCollectivity()
640            && !($this->authorizationChecker->isGranted('ROLE_REFERENT') && !in_array($object->getCollectivity(), (array) $this->userProvider->getAuthenticatedUser()->getCollectivitesReferees()))
641        ) {
642            throw new NotFoundHttpException("No object found with ID '{$id}'");
643        }
644
645        $actionEnabled = true;
646        /**
647         * @var User $user
648         */
649        $user = $this->getUser();
650        if ($object instanceof CollectivityRelated && !$this->authorizationChecker->isGranted('ROLE_ADMIN') && !$user->getServices()->isEmpty()) {
651            $actionEnabled = $object->isInUserServices($this->userProvider->getAuthenticatedUser());
652        }
653
654        if (!$actionEnabled) {
655            return $this->redirectToRoute($this->getRouteName('list'));
656        }
657
658        return $this->render($this->getTemplatingBasePath('delete'), [
659            'object' => $object,
660            'id'     => $id,
661        ]);
662    }
663
664    /**
665     * The deletion action
666     * Delete the data.
667     *
668     * @throws \Exception
669     */
670    public function deleteConfirmationAction(string $id): Response
671    {
672        /** @var Model\Survey $object */
673        $object = $this->repository->findOneById($id);
674        if (!$object) {
675            throw new NotFoundHttpException("No object found with ID '{$id}'");
676        }
677        if (
678            !$this->authorizationChecker->isGranted('ROLE_ADMIN')
679            && $this->userProvider->getAuthenticatedUser() !== $object->getCreator()
680            && $this->userProvider->getAuthenticatedUser()->getCollectivity() !== $object->getCollectivity()
681            && !($this->authorizationChecker->isGranted('ROLE_REFERENT') && !in_array($object->getCollectivity(), (array) $this->userProvider->getAuthenticatedUser()->getCollectivitesReferees()))
682        ) {
683            throw new NotFoundHttpException("No object found with ID '{$id}'");
684        }
685        if ($this->isSoftDelete()) {
686            if (!\method_exists($object, 'setDeletedAt')) {
687                throw new MethodNotImplementedException('setDeletedAt');
688            }
689            $object->setDeletedAt(new \DateTimeImmutable());
690            $this->repository->update($object);
691        } else {
692            $this->entityManager->remove($object);
693            $this->entityManager->flush();
694        }
695
696        $this->addFlash('success', $this->getFlashbagMessage('success', 'delete', $object));
697
698        return $this->redirectToRoute($this->getRouteName('list'));
699    }
700}