CRUDController.php 10.5 KB
Newer Older
Julien Jorry committed
1 2 3 4 5 6
<?php

namespace App\Controller\CRUD;

use Sonata\AdminBundle\Controller\CRUDController as Controller;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
7 8
use Symfony\Component\Form\FormRenderer;
use Symfony\Component\Form\FormView;
Julien Jorry committed
9
use Symfony\Component\HttpFoundation\RedirectResponse;
10 11
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
12 13 14
use App\Utils\CustomEntityManager;
use App\Entity\User;
use App\Entity\Flux;
Julien Jorry committed
15 16 17

class CRUDController extends Controller
{
18 19 20 21 22 23 24 25

    protected $em;

    public function __construct(CustomEntityManager $em)
    {
        $this->em = $em;
    }

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
    /**
     * Create action.
     *
     * @throws AccessDeniedException If access is not granted
     *
     * @return Response
     */
    public function createAction()
    {
        $request = $this->getRequest();
        // the key used to lookup the template
        $templateKey = 'edit';

        $this->admin->checkAccess('create');

        $class = new \ReflectionClass($this->admin->hasActiveSubClass() ? $this->admin->getActiveSubClass() : $this->admin->getClass());

        if ($class->isAbstract()) {
            return $this->renderWithExtraParams(
                '@SonataAdmin/CRUD/select_subclass.html.twig',
                [
                    'base_template' => $this->getBaseTemplate(),
                    'admin' => $this->admin,
                    'action' => 'create',
                ],
                null
            );
        }

        $newObject = $this->admin->getNewInstance();

        $preResponse = $this->preCreate($request, $newObject);
        if (null !== $preResponse) {
            return $preResponse;
        }

        $this->admin->setSubject($newObject);

        $form = $this->admin->getForm();

        $form->setData($newObject);
        $form->handleRequest($request);

        if ($form->isSubmitted()) {
            $isFormValid = $form->isValid();

            // persist if the form was valid and if in preview mode the preview was approved
            if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
                /** @phpstan-var T $submittedObject */
                $submittedObject = $form->getData();
                $this->admin->setSubject($submittedObject);
                $this->admin->checkAccess('create', $submittedObject);

                try {
                    $newObject = $this->admin->create($submittedObject);

                    if ($this->isXmlHttpRequest()) {
                        return $this->handleXmlHttpRequestSuccessResponse($request, $newObject);
                    }
                    // ADD FOR KOHINOS => test if object newly created is null to send flash message success !
                    if (null != $newObject) {
                        $this->addFlash(
                            'sonata_flash_success',
                            $this->trans(
                                'flash_create_success',
                                ['%name%' => $this->escapeHtml($this->admin->toString($newObject))],
                                'SonataAdminBundle'
                            )
                        );
                    }

                    // redirect to edit mode
                    return $this->redirectTo($newObject);
                } catch (ModelManagerException $e) {
                    $this->handleModelManagerException($e);

                    $isFormValid = false;
                }
            }

            // show an error message if the form failed validation
            if (!$isFormValid) {
                if ($this->isXmlHttpRequest() && null !== ($response = $this->handleXmlHttpRequestErrorResponse($request, $form))) {
                    return $response;
                }

                $this->addFlash(
                    'sonata_flash_error',
                    $this->trans(
                        'flash_create_error',
                        ['%name%' => $this->escapeHtml($this->admin->toString($newObject))],
                        'SonataAdminBundle'
                    )
                );
            } elseif ($this->isPreviewRequested()) {
                // pick the preview template if the form was valid and preview was requested
                $templateKey = 'preview';
                $this->admin->getShow();
            }
        }

        $formView = $form->createView();
        // set the theme for the current Admin Form
        $this->setFormTheme($formView, $this->admin->getFormTheme());

        // NEXT_MAJOR: Remove this line and use commented line below it instead
        $template = $this->admin->getTemplate($templateKey);
        // $template = $this->templateRegistry->getTemplate($templateKey);

        return $this->renderWithExtraParams($template, [
            'action' => 'create',
            'form' => $formView,
            'object' => $newObject,
            'objectId' => null,
        ], null);
    }
142

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196

    /**
     * Export data to specified format.
     *
     * @throws AccessDeniedException If access is not granted
     * @throws \RuntimeException     If the export format is invalid
     *
     */
    public function exportAction(Request $request)
    {
        set_time_limit(300); //set php time limit to 5 minutes to make sure big exports can be done
        $this->admin->checkAccess('export');

        $format = $request->get('format');

        // NEXT_MAJOR: remove the check
        if (!$this->has('sonata.admin.admin_exporter')) {
            @trigger_error(
                'Not registering the exporter bundle is deprecated since version 3.14. You must register it to be able to use the export action in 4.0.',
                \E_USER_DEPRECATED
            );
            $allowedExportFormats = (array) $this->admin->getExportFormats();

            $class = (string) $this->admin->getClass();
            $filename = sprintf(
                'export_%s_%s.%s',
                strtolower((string) substr($class, strripos($class, '\\') + 1)),
                date('Y_m_d_H_i_s', strtotime('now')),
                $format
            );
            $exporter = $this->get('sonata.admin.exporter');
        } else {
            $adminExporter = $this->get('sonata.admin.admin_exporter');
            $allowedExportFormats = $adminExporter->getAvailableFormats($this->admin);
            $filename = $adminExporter->getExportFilename($this->admin, $format);
            $exporter = $this->get('sonata.exporter.exporter');
        }

        if (!\in_array($format, $allowedExportFormats, true)) {
            throw new \RuntimeException(sprintf(
                'Export in format `%s` is not allowed for class: `%s`. Allowed formats are: `%s`',
                $format,
                $this->admin->getClass(),
                implode(', ', $allowedExportFormats)
            ));
        }

        return $exporter->getResponse(
            $format,
            $filename,
            $this->admin->getDataSourceIterator()
        );
    }

197

Julien Jorry committed
198 199 200
    public function deleteAction($id)
    {
        $request = $this->getRequest();
201 202
        $id = $request->get($this->admin->getIdParameter());
        $object = $this->admin->getObject($id);
Julien Jorry committed
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224

        if (!$object) {
            throw $this->createNotFoundException(sprintf('unable to find the object with id: %s', $id));
        }

        $currentUserId = $this->getUser()->getId(); // ID of the current user
        if ($currentUserId == $id) {
            $this->addFlash(
                'sonata_flash_error',
                'Vous ne pouvez pas supprimer votre compte !'
            );

            return $this->redirectTo($object);
        }
        if ($object->hasRole('ROLE_SUPER_ADMIN') || $object->hasRole('ROLE_ADMIN_SIEGE')) {
            $this->addFlash(
                'sonata_flash_error',
                'Vous ne pouvez pas supprimer le compte admin !'
            );

            return $this->redirectTo($object);
        }
225 226 227 228 229 230 231 232
        if ($object->hasRole('ROLE_API')) {
            $this->addFlash(
                'sonata_flash_error',
                'Vous ne pouvez pas supprimer le compte API !'
            );

            return $this->redirectTo($object);
        }
Julien Jorry committed
233

234
        // Prevent deleting user if flux related to its Adherent account exist
235 236 237 238 239 240 241 242 243 244 245 246
        if ($object instanceof User)  {
            $query = $this->em->getRepository(Flux::class)->getQueryByUser($object);

            $hasFluxAdherent = false;
            if ($object->getAdherent()) {
                $queryAdherent = $this->em->getRepository(Flux::class)->getQueryByAdherent($object->getAdherent());
                if (null != $queryAdherent && count($queryAdherent->getResult()) > 0) {
                    $hasFluxAdherent = true;
                }
            }

            if (null != $query && count($query->getResult()) > 0 || $hasFluxAdherent) {
247 248
                $this->addFlash(
                    'sonata_flash_error',
249
                    'Vous ne pouvez pas supprimer ce compte utilisateur : des flux en relation à son compte sont enregistrés.'
250 251 252 253 254 255
                );

                return $this->redirectTo($object);
            }
        }

Julien Jorry committed
256 257 258 259 260
        return parent::deleteAction($id);
    }

    public function batchActionDelete(ProxyQueryInterface $query)
    {
261
        $request = $this->getRequest();
Julien Jorry committed
262 263 264 265 266 267 268 269 270 271 272
        $currentUserId = $this->getUser()->getId(); // ID of the current user
        $selectedUsers = $query->execute();

        foreach ($selectedUsers as $selectedUser) {
            if ($selectedUser->getId() == $currentUserId) {
                $this->addFlash(
                    'sonata_flash_error',
                    'Vous ne pouvez pas supprimer votre compte !'
                );

                return new RedirectResponse(
273
                    $this->admin->generateUrl('list', ['filter' => $this->admin->getFilterParameters()])
Julien Jorry committed
274 275 276 277 278 279 280 281 282
                );
            }
            if ($selectedUser->hasRole('ROLE_SUPER_ADMIN') || $selectedUser->hasRole('ROLE_ADMIN_SIEGE')) {
                $this->addFlash(
                    'sonata_flash_error',
                    'Vous ne pouvez pas supprimer le compte admin !'
                );

                return new RedirectResponse(
283
                    $this->admin->generateUrl('list', ['filter' => $this->admin->getFilterParameters()])
Julien Jorry committed
284 285 286 287 288 289
                );
            }
        }

        return parent::batchActionDelete($query);
    }
290

291 292 293 294 295 296 297 298 299
    /**
     * Sets the admin form theme to form view. Used for compatibility between Symfony versions.
     */
    private function setFormTheme(FormView $formView, ?array $theme = null): void
    {
        $twig = $this->get('twig');

        $twig->getRuntime(FormRenderer::class)->setTheme($formView, $theme);
    }
Julien Jorry committed
300
}