vendor/sonata-project/admin-bundle/src/Controller/CRUDController.php line 287

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4.  * This file is part of the Sonata Project package.
  5.  *
  6.  * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  7.  *
  8.  * For the full copyright and license information, please view the LICENSE
  9.  * file that was distributed with this source code.
  10.  */
  11. namespace Sonata\AdminBundle\Controller;
  12. use Psr\Log\LoggerInterface;
  13. use Psr\Log\NullLogger;
  14. use Sonata\AdminBundle\Admin\AdminInterface;
  15. use Sonata\AdminBundle\Admin\Pool;
  16. use Sonata\AdminBundle\Bridge\Exporter\AdminExporter;
  17. use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
  18. use Sonata\AdminBundle\Exception\BadRequestParamHttpException;
  19. use Sonata\AdminBundle\Exception\LockException;
  20. use Sonata\AdminBundle\Exception\ModelManagerException;
  21. use Sonata\AdminBundle\Exception\ModelManagerThrowable;
  22. use Sonata\AdminBundle\Form\FormErrorIteratorToConstraintViolationList;
  23. use Sonata\AdminBundle\Model\AuditManagerInterface;
  24. use Sonata\AdminBundle\Request\AdminFetcherInterface;
  25. use Sonata\AdminBundle\Templating\TemplateRegistryInterface;
  26. use Sonata\AdminBundle\Util\AdminAclUserManagerInterface;
  27. use Sonata\AdminBundle\Util\AdminObjectAclData;
  28. use Sonata\AdminBundle\Util\AdminObjectAclManipulator;
  29. use Sonata\Exporter\ExporterInterface;
  30. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  31. use Symfony\Component\Form\FormInterface;
  32. use Symfony\Component\Form\FormRenderer;
  33. use Symfony\Component\Form\FormView;
  34. use Symfony\Component\HttpFoundation\JsonResponse;
  35. use Symfony\Component\HttpFoundation\RedirectResponse;
  36. use Symfony\Component\HttpFoundation\Request;
  37. use Symfony\Component\HttpFoundation\RequestStack;
  38. use Symfony\Component\HttpFoundation\Response;
  39. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  40. use Symfony\Component\HttpKernel\Exception\HttpException;
  41. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  42. use Symfony\Component\HttpKernel\HttpKernelInterface;
  43. use Symfony\Component\PropertyAccess\PropertyAccess;
  44. use Symfony\Component\PropertyAccess\PropertyPath;
  45. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  46. use Symfony\Component\Security\Core\User\UserInterface;
  47. use Symfony\Component\Security\Csrf\CsrfToken;
  48. use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
  49. use Symfony\Component\String\UnicodeString;
  50. use Symfony\Contracts\Translation\TranslatorInterface;
  51. use Twig\Environment;
  52. /**
  53.  * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
  54.  *
  55.  * @phpstan-template T of object
  56.  *
  57.  * @psalm-suppress MissingConstructor
  58.  *
  59.  * @see ConfigureCRUDControllerListener
  60.  */
  61. class CRUDController extends AbstractController
  62. {
  63.     /**
  64.      * The related Admin class.
  65.      *
  66.      * @var AdminInterface<object>
  67.      *
  68.      * @phpstan-var AdminInterface<T>
  69.      *
  70.      * @psalm-suppress PropertyNotSetInConstructor
  71.      */
  72.     protected $admin;
  73.     /**
  74.      * The template registry of the related Admin class.
  75.      *
  76.      * @psalm-suppress PropertyNotSetInConstructor
  77.      * @phpstan-ignore-next-line
  78.      */
  79.     private TemplateRegistryInterface $templateRegistry;
  80.     public static function getSubscribedServices(): array
  81.     {
  82.         return [
  83.             'sonata.admin.pool' => Pool::class,
  84.             'sonata.admin.audit.manager' => AuditManagerInterface::class,
  85.             'sonata.admin.object.manipulator.acl.admin' => AdminObjectAclManipulator::class,
  86.             'sonata.admin.request.fetcher' => AdminFetcherInterface::class,
  87.             'sonata.exporter.exporter' => '?'.ExporterInterface::class,
  88.             'sonata.admin.admin_exporter' => '?'.AdminExporter::class,
  89.             'sonata.admin.security.acl_user_manager' => '?'.AdminAclUserManagerInterface::class,
  90.             'controller_resolver' => 'controller_resolver',
  91.             'http_kernel' => HttpKernelInterface::class,
  92.             'logger' => '?'.LoggerInterface::class,
  93.             'translator' => TranslatorInterface::class,
  94.         ] + parent::getSubscribedServices();
  95.     }
  96.     /**
  97.      * @throws AccessDeniedException If access is not granted
  98.      */
  99.     public function listAction(Request $request): Response
  100.     {
  101.         $this->assertObjectExists($request);
  102.         $this->admin->checkAccess('list');
  103.         $preResponse $this->preList($request);
  104.         if (null !== $preResponse) {
  105.             return $preResponse;
  106.         }
  107.         $listMode $request->get('_list_mode');
  108.         if (\is_string($listMode)) {
  109.             $this->admin->setListMode($listMode);
  110.         }
  111.         $datagrid $this->admin->getDatagrid();
  112.         $formView $datagrid->getForm()->createView();
  113.         // set the theme for the current Admin Form
  114.         $this->setFormTheme($formView$this->admin->getFilterTheme());
  115.         $template $this->templateRegistry->getTemplate('list');
  116.         if ($this->container->has('sonata.admin.admin_exporter')) {
  117.             $exporter $this->container->get('sonata.admin.admin_exporter');
  118.             \assert($exporter instanceof AdminExporter);
  119.             $exportFormats $exporter->getAvailableFormats($this->admin);
  120.         }
  121.         /**
  122.          * @psalm-suppress DeprecatedMethod
  123.          */
  124.         return $this->renderWithExtraParams($template, [
  125.             'action' => 'list',
  126.             'form' => $formView,
  127.             'datagrid' => $datagrid,
  128.             'csrf_token' => $this->getCsrfToken('sonata.batch'),
  129.             'export_formats' => $exportFormats ?? $this->admin->getExportFormats(),
  130.         ]);
  131.     }
  132.     /**
  133.      * NEXT_MAJOR: Change signature to `(ProxyQueryInterface $query, Request $request).
  134.      *
  135.      * Execute a batch delete.
  136.      *
  137.      * @throws AccessDeniedException If access is not granted
  138.      *
  139.      * @phpstan-param ProxyQueryInterface<T> $query
  140.      */
  141.     public function batchActionDelete(ProxyQueryInterface $query): Response
  142.     {
  143.         $this->admin->checkAccess('batchDelete');
  144.         $modelManager $this->admin->getModelManager();
  145.         try {
  146.             $modelManager->batchDelete($this->admin->getClass(), $query);
  147.             $this->addFlash(
  148.                 'sonata_flash_success',
  149.                 $this->trans('flash_batch_delete_success', [], 'SonataAdminBundle')
  150.             );
  151.         } catch (ModelManagerException $e) {
  152.             // NEXT_MAJOR: Remove this catch.
  153.             $this->handleModelManagerException($e);
  154.             $this->addFlash(
  155.                 'sonata_flash_error',
  156.                 $this->trans('flash_batch_delete_error', [], 'SonataAdminBundle')
  157.             );
  158.         } catch (ModelManagerThrowable $e) {
  159.             $errorMessage $this->handleModelManagerThrowable($e);
  160.             $this->addFlash(
  161.                 'sonata_flash_error',
  162.                 $errorMessage ?? $this->trans('flash_batch_delete_error', [], 'SonataAdminBundle')
  163.             );
  164.         }
  165.         return $this->redirectToList();
  166.     }
  167.     /**
  168.      * @throws NotFoundHttpException If the object does not exist
  169.      * @throws AccessDeniedException If access is not granted
  170.      */
  171.     public function deleteAction(Request $request): Response
  172.     {
  173.         $object $this->assertObjectExists($requesttrue);
  174.         \assert(null !== $object);
  175.         $this->checkParentChildAssociation($request$object);
  176.         $this->admin->checkAccess('delete'$object);
  177.         $preResponse $this->preDelete($request$object);
  178.         if (null !== $preResponse) {
  179.             return $preResponse;
  180.         }
  181.         if (\in_array($request->getMethod(), [Request::METHOD_POSTRequest::METHOD_DELETE], true)) {
  182.             // check the csrf token
  183.             $this->validateCsrfToken($request'sonata.delete');
  184.             $objectName $this->admin->toString($object);
  185.             try {
  186.                 $this->admin->delete($object);
  187.                 if ($this->isXmlHttpRequest($request)) {
  188.                     return $this->renderJson(['result' => 'ok']);
  189.                 }
  190.                 $this->addFlash(
  191.                     'sonata_flash_success',
  192.                     $this->trans(
  193.                         'flash_delete_success',
  194.                         ['%name%' => $this->escapeHtml($objectName)],
  195.                         'SonataAdminBundle'
  196.                     )
  197.                 );
  198.             } catch (ModelManagerException $e) {
  199.                 // NEXT_MAJOR: Remove this catch.
  200.                 $this->handleModelManagerException($e);
  201.                 if ($this->isXmlHttpRequest($request)) {
  202.                     return $this->renderJson(['result' => 'error']);
  203.                 }
  204.                 $this->addFlash(
  205.                     'sonata_flash_error',
  206.                     $this->trans(
  207.                         'flash_delete_error',
  208.                         ['%name%' => $this->escapeHtml($objectName)],
  209.                         'SonataAdminBundle'
  210.                     )
  211.                 );
  212.             } catch (ModelManagerThrowable $e) {
  213.                 $errorMessage $this->handleModelManagerThrowable($e);
  214.                 if ($this->isXmlHttpRequest($request)) {
  215.                     return $this->renderJson(['result' => 'error'], Response::HTTP_OK, []);
  216.                 }
  217.                 $this->addFlash(
  218.                     'sonata_flash_error',
  219.                     $errorMessage ?? $this->trans(
  220.                         'flash_delete_error',
  221.                         ['%name%' => $this->escapeHtml($objectName)],
  222.                         'SonataAdminBundle'
  223.                     )
  224.                 );
  225.             }
  226.             return $this->redirectTo($request$object);
  227.         }
  228.         $template $this->templateRegistry->getTemplate('delete');
  229.         /**
  230.          * @psalm-suppress DeprecatedMethod
  231.          */
  232.         return $this->renderWithExtraParams($template, [
  233.             'object' => $object,
  234.             'action' => 'delete',
  235.             'csrf_token' => $this->getCsrfToken('sonata.delete'),
  236.         ]);
  237.     }
  238.     /**
  239.      * @throws NotFoundHttpException If the object does not exist
  240.      * @throws AccessDeniedException If access is not granted
  241.      */
  242.     public function editAction(Request $request): Response
  243.     {
  244.         // the key used to lookup the template
  245.         $templateKey 'edit';
  246.         $existingObject $this->assertObjectExists($requesttrue);
  247.         \assert(null !== $existingObject);
  248.         $this->checkParentChildAssociation($request$existingObject);
  249.         $this->admin->checkAccess('edit'$existingObject);
  250.         $preResponse $this->preEdit($request$existingObject);
  251.         if (null !== $preResponse) {
  252.             return $preResponse;
  253.         }
  254.         $this->admin->setSubject($existingObject);
  255.         $objectId $this->admin->getNormalizedIdentifier($existingObject);
  256.         \assert(null !== $objectId);
  257.         $form $this->admin->getForm();
  258.         $form->setData($existingObject);
  259.         $form->handleRequest($request);
  260.         if ($form->isSubmitted()) {
  261.             $isFormValid $form->isValid();
  262.             // persist if the form was valid and if in preview mode the preview was approved
  263.             if ($isFormValid && (!$this->isInPreviewMode($request) || $this->isPreviewApproved($request))) {
  264.                 /** @phpstan-var T $submittedObject */
  265.                 $submittedObject $form->getData();
  266.                 $this->admin->setSubject($submittedObject);
  267.                 try {
  268.                     $existingObject $this->admin->update($submittedObject);
  269.                     if ($this->isXmlHttpRequest($request)) {
  270.                         return $this->handleXmlHttpRequestSuccessResponse($request$existingObject);
  271.                     }
  272.                     $this->addFlash(
  273.                         'sonata_flash_success',
  274.                         $this->trans(
  275.                             'flash_edit_success',
  276.                             ['%name%' => $this->escapeHtml($this->admin->toString($existingObject))],
  277.                             'SonataAdminBundle'
  278.                         )
  279.                     );
  280.                     // redirect to edit mode
  281.                     return $this->redirectTo($request$existingObject);
  282.                 } catch (ModelManagerException $e) {
  283.                     // NEXT_MAJOR: Remove this catch.
  284.                     $this->handleModelManagerException($e);
  285.                     $isFormValid false;
  286.                 } catch (ModelManagerThrowable $e) {
  287.                     $errorMessage $this->handleModelManagerThrowable($e);
  288.                     $isFormValid false;
  289.                 } catch (LockException) {
  290.                     $this->addFlash('sonata_flash_error'$this->trans('flash_lock_error', [
  291.                         '%name%' => $this->escapeHtml($this->admin->toString($existingObject)),
  292.                         '%link_start%' => sprintf('<a href="%s">'$this->admin->generateObjectUrl('edit'$existingObject)),
  293.                         '%link_end%' => '</a>',
  294.                     ], 'SonataAdminBundle'));
  295.                 }
  296.             }
  297.             // show an error message if the form failed validation
  298.             if (!$isFormValid) {
  299.                 if ($this->isXmlHttpRequest($request) && null !== ($response $this->handleXmlHttpRequestErrorResponse($request$form))) {
  300.                     return $response;
  301.                 }
  302.                 $this->addFlash(
  303.                     'sonata_flash_error',
  304.                     $errorMessage ?? $this->trans(
  305.                         'flash_edit_error',
  306.                         ['%name%' => $this->escapeHtml($this->admin->toString($existingObject))],
  307.                         'SonataAdminBundle'
  308.                     )
  309.                 );
  310.             } elseif ($this->isPreviewRequested($request)) {
  311.                 // enable the preview template if the form was valid and preview was requested
  312.                 $templateKey 'preview';
  313.                 $this->admin->getShow();
  314.             }
  315.         }
  316.         $formView $form->createView();
  317.         // set the theme for the current Admin Form
  318.         $this->setFormTheme($formView$this->admin->getFormTheme());
  319.         $template $this->templateRegistry->getTemplate($templateKey);
  320.         /**
  321.          * @psalm-suppress DeprecatedMethod
  322.          */
  323.         return $this->renderWithExtraParams($template, [
  324.             'action' => 'edit',
  325.             'form' => $formView,
  326.             'object' => $existingObject,
  327.             'objectId' => $objectId,
  328.         ]);
  329.     }
  330.     /**
  331.      * @throws NotFoundHttpException If the HTTP method is not POST
  332.      * @throws \RuntimeException     If the batch action is not defined
  333.      */
  334.     public function batchAction(Request $request): Response
  335.     {
  336.         $restMethod $request->getMethod();
  337.         if (Request::METHOD_POST !== $restMethod) {
  338.             throw $this->createNotFoundException(sprintf(
  339.                 'Invalid request method given "%s", %s expected',
  340.                 $restMethod,
  341.                 Request::METHOD_POST
  342.             ));
  343.         }
  344.         // check the csrf token
  345.         $this->validateCsrfToken($request'sonata.batch');
  346.         $confirmation $request->get('confirmation'false);
  347.         $forwardedRequest $request->duplicate();
  348.         $encodedData $request->get('data');
  349.         if (null === $encodedData) {
  350.             $action $forwardedRequest->request->get('action');
  351.             $bag $request->request;
  352.             $idx $bag->all('idx');
  353.             $allElements $forwardedRequest->request->getBoolean('all_elements');
  354.             $forwardedRequest->request->set('idx'$idx);
  355.             $forwardedRequest->request->set('all_elements', (string) $allElements);
  356.             $data $forwardedRequest->request->all();
  357.             $data['all_elements'] = $allElements;
  358.             unset($data['_sonata_csrf_token']);
  359.         } else {
  360.             if (!\is_string($encodedData)) {
  361.                 throw new BadRequestParamHttpException('data''string'$encodedData);
  362.             }
  363.             try {
  364.                 $data json_decode($encodedDatatrue512\JSON_THROW_ON_ERROR);
  365.             } catch (\JsonException) {
  366.                 throw new BadRequestHttpException('Unable to decode batch data');
  367.             }
  368.             $action $data['action'];
  369.             $idx = (array) ($data['idx'] ?? []);
  370.             $allElements = (bool) ($data['all_elements'] ?? false);
  371.             $forwardedRequest->request->replace(array_merge($forwardedRequest->request->all(), $data));
  372.         }
  373.         if (!\is_string($action)) {
  374.             throw new \RuntimeException('The action is not defined');
  375.         }
  376.         $camelizedAction = (new UnicodeString($action))->camel()->title(true)->toString();
  377.         try {
  378.             $batchActionExecutable $this->getBatchActionExecutable($action);
  379.         } catch (\Throwable $error) {
  380.             $finalAction sprintf('batchAction%s'$camelizedAction);
  381.             throw new \RuntimeException(sprintf('A `%s::%s` method must be callable or create a `controller` configuration for your batch action.'$this->admin->getBaseControllerName(), $finalAction), 0$error);
  382.         }
  383.         $batchAction $this->admin->getBatchActions()[$action];
  384.         $isRelevantAction sprintf('batchAction%sIsRelevant'$camelizedAction);
  385.         if (method_exists($this$isRelevantAction)) {
  386.             // NEXT_MAJOR: Remove if above in sonata-project/admin-bundle 5.0
  387.             @trigger_error(sprintf(
  388.                 'The is relevant hook via "%s()" is deprecated since sonata-project/admin-bundle 4.12'
  389.                 .' and will not be call in 5.0. Move the logic to your controller.',
  390.                 $isRelevantAction,
  391.             ), \E_USER_DEPRECATED);
  392.             $nonRelevantMessage $this->$isRelevantAction($idx$allElements$forwardedRequest);
  393.         } else {
  394.             $nonRelevantMessage !== \count($idx) || $allElements// at least one item is selected
  395.         }
  396.         if (!$nonRelevantMessage) { // default non relevant message (if false of null)
  397.             $nonRelevantMessage 'flash_batch_empty';
  398.         }
  399.         $datagrid $this->admin->getDatagrid();
  400.         $datagrid->buildPager();
  401.         if (true !== $nonRelevantMessage) {
  402.             $this->addFlash(
  403.                 'sonata_flash_info',
  404.                 $this->trans($nonRelevantMessage, [], 'SonataAdminBundle')
  405.             );
  406.             return $this->redirectToList();
  407.         }
  408.         $askConfirmation $batchAction['ask_confirmation'] ?? true;
  409.         if (true === $askConfirmation && 'ok' !== $confirmation) {
  410.             $actionLabel $batchAction['label'];
  411.             $batchTranslationDomain $batchAction['translation_domain'] ??
  412.                 $this->admin->getTranslationDomain();
  413.             $formView $datagrid->getForm()->createView();
  414.             $this->setFormTheme($formView$this->admin->getFilterTheme());
  415.             $template $batchAction['template'] ?? $this->templateRegistry->getTemplate('batch_confirmation');
  416.             /**
  417.              * @psalm-suppress DeprecatedMethod
  418.              */
  419.             return $this->renderWithExtraParams($template, [
  420.                 'action' => 'list',
  421.                 'action_label' => $actionLabel,
  422.                 'batch_translation_domain' => $batchTranslationDomain,
  423.                 'datagrid' => $datagrid,
  424.                 'form' => $formView,
  425.                 'data' => $data,
  426.                 'csrf_token' => $this->getCsrfToken('sonata.batch'),
  427.             ]);
  428.         }
  429.         $query $datagrid->getQuery();
  430.         $query->setFirstResult(null);
  431.         $query->setMaxResults(null);
  432.         $this->admin->preBatchAction($action$query$idx$allElements);
  433.         foreach ($this->admin->getExtensions() as $extension) {
  434.             // NEXT_MAJOR: Remove the if-statement around the call to `$extension->preBatchAction()`
  435.             if (method_exists($extension'preBatchAction')) {
  436.                 $extension->preBatchAction($this->admin$action$query$idx$allElements);
  437.             }
  438.         }
  439.         if (\count($idx) > 0) {
  440.             $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query$idx);
  441.         } elseif (!$allElements) {
  442.             $this->addFlash(
  443.                 'sonata_flash_info',
  444.                 $this->trans('flash_batch_no_elements_processed', [], 'SonataAdminBundle')
  445.             );
  446.             return $this->redirectToList();
  447.         }
  448.         return \call_user_func($batchActionExecutable$query$forwardedRequest);
  449.     }
  450.     /**
  451.      * @throws AccessDeniedException If access is not granted
  452.      */
  453.     public function createAction(Request $request): Response
  454.     {
  455.         $this->assertObjectExists($request);
  456.         $this->admin->checkAccess('create');
  457.         // the key used to lookup the template
  458.         $templateKey 'edit';
  459.         $class = new \ReflectionClass($this->admin->hasActiveSubClass() ? $this->admin->getActiveSubClass() : $this->admin->getClass());
  460.         if ($class->isAbstract()) {
  461.             /**
  462.              * @psalm-suppress DeprecatedMethod
  463.              */
  464.             return $this->renderWithExtraParams(
  465.                 '@SonataAdmin/CRUD/select_subclass.html.twig',
  466.                 [
  467.                     'action' => 'create',
  468.                 ],
  469.             );
  470.         }
  471.         $newObject $this->admin->getNewInstance();
  472.         $preResponse $this->preCreate($request$newObject);
  473.         if (null !== $preResponse) {
  474.             return $preResponse;
  475.         }
  476.         $this->admin->setSubject($newObject);
  477.         $form $this->admin->getForm();
  478.         $form->setData($newObject);
  479.         $form->handleRequest($request);
  480.         if ($form->isSubmitted()) {
  481.             $isFormValid $form->isValid();
  482.             // persist if the form was valid and if in preview mode the preview was approved
  483.             if ($isFormValid && (!$this->isInPreviewMode($request) || $this->isPreviewApproved($request))) {
  484.                 /** @phpstan-var T $submittedObject */
  485.                 $submittedObject $form->getData();
  486.                 $this->admin->setSubject($submittedObject);
  487.                 try {
  488.                     $newObject $this->admin->create($submittedObject);
  489.                     if ($this->isXmlHttpRequest($request)) {
  490.                         return $this->handleXmlHttpRequestSuccessResponse($request$newObject);
  491.                     }
  492.                     $this->addFlash(
  493.                         'sonata_flash_success',
  494.                         $this->trans(
  495.                             'flash_create_success',
  496.                             ['%name%' => $this->escapeHtml($this->admin->toString($newObject))],
  497.                             'SonataAdminBundle'
  498.                         )
  499.                     );
  500.                     // redirect to edit mode
  501.                     return $this->redirectTo($request$newObject);
  502.                 } catch (ModelManagerException $e) {
  503.                     // NEXT_MAJOR: Remove this catch.
  504.                     $this->handleModelManagerException($e);
  505.                     $isFormValid false;
  506.                 } catch (ModelManagerThrowable $e) {
  507.                     $errorMessage $this->handleModelManagerThrowable($e);
  508.                     $isFormValid false;
  509.                 }
  510.             }
  511.             // show an error message if the form failed validation
  512.             if (!$isFormValid) {
  513.                 if ($this->isXmlHttpRequest($request) && null !== ($response $this->handleXmlHttpRequestErrorResponse($request$form))) {
  514.                     return $response;
  515.                 }
  516.                 $this->addFlash(
  517.                     'sonata_flash_error',
  518.                     $errorMessage ?? $this->trans(
  519.                         'flash_create_error',
  520.                         ['%name%' => $this->escapeHtml($this->admin->toString($newObject))],
  521.                         'SonataAdminBundle'
  522.                     )
  523.                 );
  524.             } elseif ($this->isPreviewRequested($request)) {
  525.                 // pick the preview template if the form was valid and preview was requested
  526.                 $templateKey 'preview';
  527.                 $this->admin->getShow();
  528.             }
  529.         }
  530.         $formView $form->createView();
  531.         // set the theme for the current Admin Form
  532.         $this->setFormTheme($formView$this->admin->getFormTheme());
  533.         $template $this->templateRegistry->getTemplate($templateKey);
  534.         /**
  535.          * @psalm-suppress DeprecatedMethod
  536.          */
  537.         return $this->renderWithExtraParams($template, [
  538.             'action' => 'create',
  539.             'form' => $formView,
  540.             'object' => $newObject,
  541.             'objectId' => null,
  542.         ]);
  543.     }
  544.     /**
  545.      * @throws NotFoundHttpException If the object does not exist
  546.      * @throws AccessDeniedException If access is not granted
  547.      */
  548.     public function showAction(Request $request): Response
  549.     {
  550.         $object $this->assertObjectExists($requesttrue);
  551.         \assert(null !== $object);
  552.         $this->checkParentChildAssociation($request$object);
  553.         $this->admin->checkAccess('show'$object);
  554.         $preResponse $this->preShow($request$object);
  555.         if (null !== $preResponse) {
  556.             return $preResponse;
  557.         }
  558.         $this->admin->setSubject($object);
  559.         $fields $this->admin->getShow();
  560.         $template $this->templateRegistry->getTemplate('show');
  561.         /**
  562.          * @psalm-suppress DeprecatedMethod
  563.          */
  564.         return $this->renderWithExtraParams($template, [
  565.             'action' => 'show',
  566.             'object' => $object,
  567.             'elements' => $fields,
  568.         ]);
  569.     }
  570.     /**
  571.      * Show history revisions for object.
  572.      *
  573.      * @throws AccessDeniedException If access is not granted
  574.      * @throws NotFoundHttpException If the object does not exist or the audit reader is not available
  575.      */
  576.     public function historyAction(Request $request): Response
  577.     {
  578.         $object $this->assertObjectExists($requesttrue);
  579.         \assert(null !== $object);
  580.         $this->admin->checkAccess('history'$object);
  581.         $objectId $this->admin->getNormalizedIdentifier($object);
  582.         \assert(null !== $objectId);
  583.         $manager $this->container->get('sonata.admin.audit.manager');
  584.         \assert($manager instanceof AuditManagerInterface);
  585.         if (!$manager->hasReader($this->admin->getClass())) {
  586.             throw $this->createNotFoundException(sprintf(
  587.                 'unable to find the audit reader for class : %s',
  588.                 $this->admin->getClass()
  589.             ));
  590.         }
  591.         $reader $manager->getReader($this->admin->getClass());
  592.         $revisions $reader->findRevisions($this->admin->getClass(), $objectId);
  593.         $template $this->templateRegistry->getTemplate('history');
  594.         /**
  595.          * @psalm-suppress DeprecatedMethod
  596.          */
  597.         return $this->renderWithExtraParams($template, [
  598.             'action' => 'history',
  599.             'object' => $object,
  600.             'revisions' => $revisions,
  601.             'currentRevision' => current($revisions),
  602.         ]);
  603.     }
  604.     /**
  605.      * View history revision of object.
  606.      *
  607.      * @throws AccessDeniedException If access is not granted
  608.      * @throws NotFoundHttpException If the object or revision does not exist or the audit reader is not available
  609.      */
  610.     public function historyViewRevisionAction(Request $requeststring $revision): Response
  611.     {
  612.         $object $this->assertObjectExists($requesttrue);
  613.         \assert(null !== $object);
  614.         $this->admin->checkAccess('historyViewRevision'$object);
  615.         $objectId $this->admin->getNormalizedIdentifier($object);
  616.         \assert(null !== $objectId);
  617.         $manager $this->container->get('sonata.admin.audit.manager');
  618.         \assert($manager instanceof AuditManagerInterface);
  619.         if (!$manager->hasReader($this->admin->getClass())) {
  620.             throw $this->createNotFoundException(sprintf(
  621.                 'unable to find the audit reader for class : %s',
  622.                 $this->admin->getClass()
  623.             ));
  624.         }
  625.         $reader $manager->getReader($this->admin->getClass());
  626.         // retrieve the revisioned object
  627.         $object $reader->find($this->admin->getClass(), $objectId$revision);
  628.         if (null === $object) {
  629.             throw $this->createNotFoundException(sprintf(
  630.                 'unable to find the targeted object `%s` from the revision `%s` with classname : `%s`',
  631.                 $objectId,
  632.                 $revision,
  633.                 $this->admin->getClass()
  634.             ));
  635.         }
  636.         $this->admin->setSubject($object);
  637.         $template $this->templateRegistry->getTemplate('show');
  638.         /**
  639.          * @psalm-suppress DeprecatedMethod
  640.          */
  641.         return $this->renderWithExtraParams($template, [
  642.             'action' => 'show',
  643.             'object' => $object,
  644.             'elements' => $this->admin->getShow(),
  645.         ]);
  646.     }
  647.     /**
  648.      * Compare history revisions of object.
  649.      *
  650.      * @throws AccessDeniedException If access is not granted
  651.      * @throws NotFoundHttpException If the object or revision does not exist or the audit reader is not available
  652.      */
  653.     public function historyCompareRevisionsAction(Request $requeststring $baseRevisionstring $compareRevision): Response
  654.     {
  655.         $this->admin->checkAccess('historyCompareRevisions');
  656.         $object $this->assertObjectExists($requesttrue);
  657.         \assert(null !== $object);
  658.         $objectId $this->admin->getNormalizedIdentifier($object);
  659.         \assert(null !== $objectId);
  660.         $manager $this->container->get('sonata.admin.audit.manager');
  661.         \assert($manager instanceof AuditManagerInterface);
  662.         if (!$manager->hasReader($this->admin->getClass())) {
  663.             throw $this->createNotFoundException(sprintf(
  664.                 'unable to find the audit reader for class : %s',
  665.                 $this->admin->getClass()
  666.             ));
  667.         }
  668.         $reader $manager->getReader($this->admin->getClass());
  669.         // retrieve the base revision
  670.         $baseObject $reader->find($this->admin->getClass(), $objectId$baseRevision);
  671.         if (null === $baseObject) {
  672.             throw $this->createNotFoundException(sprintf(
  673.                 'unable to find the targeted object `%s` from the revision `%s` with classname : `%s`',
  674.                 $objectId,
  675.                 $baseRevision,
  676.                 $this->admin->getClass()
  677.             ));
  678.         }
  679.         // retrieve the compare revision
  680.         $compareObject $reader->find($this->admin->getClass(), $objectId$compareRevision);
  681.         if (null === $compareObject) {
  682.             throw $this->createNotFoundException(sprintf(
  683.                 'unable to find the targeted object `%s` from the revision `%s` with classname : `%s`',
  684.                 $objectId,
  685.                 $compareRevision,
  686.                 $this->admin->getClass()
  687.             ));
  688.         }
  689.         $this->admin->setSubject($baseObject);
  690.         $template $this->templateRegistry->getTemplate('show_compare');
  691.         /**
  692.          * @psalm-suppress DeprecatedMethod
  693.          */
  694.         return $this->renderWithExtraParams($template, [
  695.             'action' => 'show',
  696.             'object' => $baseObject,
  697.             'object_compare' => $compareObject,
  698.             'elements' => $this->admin->getShow(),
  699.         ]);
  700.     }
  701.     /**
  702.      * Export data to specified format.
  703.      *
  704.      * @throws AccessDeniedException If access is not granted
  705.      * @throws \RuntimeException     If the export format is invalid
  706.      */
  707.     public function exportAction(Request $request): Response
  708.     {
  709.         $this->admin->checkAccess('export');
  710.         $format $request->get('format');
  711.         if (!\is_string($format)) {
  712.             throw new BadRequestParamHttpException('format''string'$format);
  713.         }
  714.         $adminExporter $this->container->get('sonata.admin.admin_exporter');
  715.         \assert($adminExporter instanceof AdminExporter);
  716.         $allowedExportFormats $adminExporter->getAvailableFormats($this->admin);
  717.         $filename $adminExporter->getExportFilename($this->admin$format);
  718.         $exporter $this->container->get('sonata.exporter.exporter');
  719.         \assert($exporter instanceof ExporterInterface);
  720.         if (!\in_array($format$allowedExportFormatstrue)) {
  721.             throw new \RuntimeException(sprintf(
  722.                 'Export in format `%s` is not allowed for class: `%s`. Allowed formats are: `%s`',
  723.                 $format,
  724.                 $this->admin->getClass(),
  725.                 implode(', '$allowedExportFormats)
  726.             ));
  727.         }
  728.         return $exporter->getResponse(
  729.             $format,
  730.             $filename,
  731.             $this->admin->getDataSourceIterator()
  732.         );
  733.     }
  734.     /**
  735.      * Returns the Response object associated to the acl action.
  736.      *
  737.      * @throws AccessDeniedException If access is not granted
  738.      * @throws NotFoundHttpException If the object does not exist or the ACL is not enabled
  739.      */
  740.     public function aclAction(Request $request): Response
  741.     {
  742.         if (!$this->admin->isAclEnabled()) {
  743.             throw $this->createNotFoundException('ACL are not enabled for this admin');
  744.         }
  745.         $object $this->assertObjectExists($requesttrue);
  746.         \assert(null !== $object);
  747.         $this->admin->checkAccess('acl'$object);
  748.         $this->admin->setSubject($object);
  749.         $aclUsers $this->getAclUsers();
  750.         $aclRoles $this->getAclRoles();
  751.         $adminObjectAclManipulator $this->container->get('sonata.admin.object.manipulator.acl.admin');
  752.         \assert($adminObjectAclManipulator instanceof AdminObjectAclManipulator);
  753.         $adminObjectAclData = new AdminObjectAclData(
  754.             $this->admin,
  755.             $object,
  756.             $aclUsers,
  757.             $adminObjectAclManipulator->getMaskBuilderClass(),
  758.             $aclRoles
  759.         );
  760.         $aclUsersForm $adminObjectAclManipulator->createAclUsersForm($adminObjectAclData);
  761.         $aclRolesForm $adminObjectAclManipulator->createAclRolesForm($adminObjectAclData);
  762.         if (Request::METHOD_POST === $request->getMethod()) {
  763.             if ($request->request->has(AdminObjectAclManipulator::ACL_USERS_FORM_NAME)) {
  764.                 $form $aclUsersForm;
  765.                 $updateMethod 'updateAclUsers';
  766.             } elseif ($request->request->has(AdminObjectAclManipulator::ACL_ROLES_FORM_NAME)) {
  767.                 $form $aclRolesForm;
  768.                 $updateMethod 'updateAclRoles';
  769.             }
  770.             if (isset($form$updateMethod)) {
  771.                 $form->handleRequest($request);
  772.                 if ($form->isValid()) {
  773.                     $adminObjectAclManipulator->$updateMethod($adminObjectAclData);
  774.                     $this->addFlash(
  775.                         'sonata_flash_success',
  776.                         $this->trans('flash_acl_edit_success', [], 'SonataAdminBundle')
  777.                     );
  778.                     return new RedirectResponse($this->admin->generateObjectUrl('acl'$object));
  779.                 }
  780.             }
  781.         }
  782.         $template $this->templateRegistry->getTemplate('acl');
  783.         /**
  784.          * @psalm-suppress DeprecatedMethod
  785.          */
  786.         return $this->renderWithExtraParams($template, [
  787.             'action' => 'acl',
  788.             'permissions' => $adminObjectAclData->getUserPermissions(),
  789.             'object' => $object,
  790.             'users' => $aclUsers,
  791.             'roles' => $aclRoles,
  792.             'aclUsersForm' => $aclUsersForm->createView(),
  793.             'aclRolesForm' => $aclRolesForm->createView(),
  794.         ]);
  795.     }
  796.     /**
  797.      * Contextualize the admin class depends on the current request.
  798.      *
  799.      * @throws \InvalidArgumentException
  800.      */
  801.     final public function configureAdmin(Request $request): void
  802.     {
  803.         $adminFetcher $this->container->get('sonata.admin.request.fetcher');
  804.         \assert($adminFetcher instanceof AdminFetcherInterface);
  805.         /** @var AdminInterface<T> $admin */
  806.         $admin $adminFetcher->get($request);
  807.         $this->admin $admin;
  808.         if (!$this->admin->hasTemplateRegistry()) {
  809.             throw new \RuntimeException(sprintf(
  810.                 'Unable to find the template registry related to the current admin (%s).',
  811.                 $this->admin->getCode()
  812.             ));
  813.         }
  814.         $this->templateRegistry $this->admin->getTemplateRegistry();
  815.     }
  816.     /**
  817.      * Add twig globals which are used in every template.
  818.      */
  819.     final public function setTwigGlobals(Request $request): void
  820.     {
  821.         $this->setTwigGlobal('admin'$this->admin);
  822.         if ($this->isXmlHttpRequest($request)) {
  823.             $baseTemplate $this->templateRegistry->getTemplate('ajax');
  824.         } else {
  825.             $baseTemplate $this->templateRegistry->getTemplate('layout');
  826.         }
  827.         $this->setTwigGlobal('base_template'$baseTemplate);
  828.     }
  829.     /**
  830.      * Renders a view while passing mandatory parameters on to the template.
  831.      *
  832.      * @param string               $view       The view name
  833.      * @param array<string, mixed> $parameters An array of parameters to pass to the view
  834.      *
  835.      * @deprecated since sonata-project/admin-bundle version 4.x
  836.      *
  837.      *  NEXT_MAJOR: Remove this method
  838.      */
  839.     final protected function renderWithExtraParams(string $view, array $parameters = [], ?Response $response null): Response
  840.     {
  841.         /**
  842.          * @psalm-suppress DeprecatedMethod
  843.          */
  844.         return $this->render($view$this->addRenderExtraParams($parameters), $response);
  845.     }
  846.     /**
  847.      * @param array<string, mixed> $parameters
  848.      *
  849.      * @return array<string, mixed>
  850.      *
  851.      * @deprecated since sonata-project/admin-bundle version 4.x
  852.      *
  853.      * NEXT_MAJOR: Remove this method
  854.      */
  855.     protected function addRenderExtraParams(array $parameters = []): array
  856.     {
  857.         $parameters['admin'] ??= $this->admin;
  858.         /**
  859.          * @psalm-suppress DeprecatedMethod
  860.          */
  861.         $parameters['base_template'] ??= $this->getBaseTemplate();
  862.         return $parameters;
  863.     }
  864.     /**
  865.      * @param mixed[] $headers
  866.      */
  867.     final protected function renderJson(mixed $dataint $status Response::HTTP_OK, array $headers = []): JsonResponse
  868.     {
  869.         return new JsonResponse($data$status$headers);
  870.     }
  871.     /**
  872.      * Returns true if the request is a XMLHttpRequest.
  873.      *
  874.      * @return bool True if the request is an XMLHttpRequest, false otherwise
  875.      */
  876.     final protected function isXmlHttpRequest(Request $request): bool
  877.     {
  878.         return $request->isXmlHttpRequest()
  879.             || $request->request->getBoolean('_xml_http_request')
  880.             || $request->query->getBoolean('_xml_http_request');
  881.     }
  882.     /**
  883.      * Proxy for the logger service of the container.
  884.      * If no such service is found, a NullLogger is returned.
  885.      */
  886.     protected function getLogger(): LoggerInterface
  887.     {
  888.         if ($this->container->has('logger')) {
  889.             $logger $this->container->get('logger');
  890.             \assert($logger instanceof LoggerInterface);
  891.             return $logger;
  892.         }
  893.         return new NullLogger();
  894.     }
  895.     /**
  896.      * Returns the base template name.
  897.      *
  898.      * @return string The template name
  899.      *
  900.      * @deprecated since sonata-project/admin-bundle version 4.x
  901.      *
  902.      *  NEXT_MAJOR: Remove this method
  903.      */
  904.     protected function getBaseTemplate(): string
  905.     {
  906.         $requestStack $this->container->get('request_stack');
  907.         \assert($requestStack instanceof RequestStack);
  908.         $request $requestStack->getCurrentRequest();
  909.         \assert(null !== $request);
  910.         if ($this->isXmlHttpRequest($request)) {
  911.             return $this->templateRegistry->getTemplate('ajax');
  912.         }
  913.         return $this->templateRegistry->getTemplate('layout');
  914.     }
  915.     /**
  916.      * @throws \Exception
  917.      */
  918.     protected function handleModelManagerException(\Exception $exception): void
  919.     {
  920.         if ($exception instanceof ModelManagerThrowable) {
  921.             $this->handleModelManagerThrowable($exception);
  922.             return;
  923.         }
  924.         @trigger_error(sprintf(
  925.             'The method "%s()" is deprecated since sonata-project/admin-bundle 3.107 and will be removed in 5.0.',
  926.             __METHOD__
  927.         ), \E_USER_DEPRECATED);
  928.         $debug $this->getParameter('kernel.debug');
  929.         \assert(\is_bool($debug));
  930.         if ($debug) {
  931.             throw $exception;
  932.         }
  933.         $context = ['exception' => $exception];
  934.         if (null !== $exception->getPrevious()) {
  935.             $context['previous_exception_message'] = $exception->getPrevious()->getMessage();
  936.         }
  937.         $this->getLogger()->error($exception->getMessage(), $context);
  938.     }
  939.     /**
  940.      * NEXT_MAJOR: Add typehint.
  941.      *
  942.      * @throws ModelManagerThrowable
  943.      *
  944.      * @return string|null A custom error message to display in the flag bag instead of the generic one
  945.      */
  946.     protected function handleModelManagerThrowable(ModelManagerThrowable $exception)
  947.     {
  948.         $debug $this->getParameter('kernel.debug');
  949.         \assert(\is_bool($debug));
  950.         if ($debug) {
  951.             throw $exception;
  952.         }
  953.         $context = ['exception' => $exception];
  954.         if (null !== $exception->getPrevious()) {
  955.             $context['previous_exception_message'] = $exception->getPrevious()->getMessage();
  956.         }
  957.         $this->getLogger()->error($exception->getMessage(), $context);
  958.         return null;
  959.     }
  960.     /**
  961.      * Redirect the user depend on this choice.
  962.      *
  963.      * @phpstan-param T $object
  964.      */
  965.     protected function redirectTo(Request $requestobject $object): RedirectResponse
  966.     {
  967.         if (null !== $request->get('btn_update_and_list')) {
  968.             return $this->redirectToList();
  969.         }
  970.         if (null !== $request->get('btn_create_and_list')) {
  971.             return $this->redirectToList();
  972.         }
  973.         if (null !== $request->get('btn_create_and_create')) {
  974.             $params = [];
  975.             if ($this->admin->hasActiveSubClass()) {
  976.                 $params['subclass'] = $request->get('subclass');
  977.             }
  978.             return new RedirectResponse($this->admin->generateUrl('create'$params));
  979.         }
  980.         if (null !== $request->get('btn_delete')) {
  981.             return $this->redirectToList();
  982.         }
  983.         foreach (['edit''show'] as $route) {
  984.             if ($this->admin->hasRoute($route) && $this->admin->hasAccess($route$object)) {
  985.                 $url $this->admin->generateObjectUrl(
  986.                     $route,
  987.                     $object,
  988.                     $this->getSelectedTab($request)
  989.                 );
  990.                 return new RedirectResponse($url);
  991.             }
  992.         }
  993.         return $this->redirectToList();
  994.     }
  995.     /**
  996.      * Redirects the user to the list view.
  997.      */
  998.     final protected function redirectToList(): RedirectResponse
  999.     {
  1000.         $parameters = [];
  1001.         $filter $this->admin->getFilterParameters();
  1002.         if ([] !== $filter) {
  1003.             $parameters['filter'] = $filter;
  1004.         }
  1005.         return $this->redirect($this->admin->generateUrl('list'$parameters));
  1006.     }
  1007.     /**
  1008.      * Returns true if the preview is requested to be shown.
  1009.      */
  1010.     final protected function isPreviewRequested(Request $request): bool
  1011.     {
  1012.         return null !== $request->get('btn_preview');
  1013.     }
  1014.     /**
  1015.      * Returns true if the preview has been approved.
  1016.      */
  1017.     final protected function isPreviewApproved(Request $request): bool
  1018.     {
  1019.         return null !== $request->get('btn_preview_approve');
  1020.     }
  1021.     /**
  1022.      * Returns true if the request is in the preview workflow.
  1023.      *
  1024.      * That means either a preview is requested or the preview has already been shown
  1025.      * and it got approved/declined.
  1026.      */
  1027.     final protected function isInPreviewMode(Request $request): bool
  1028.     {
  1029.         return $this->admin->supportsPreviewMode()
  1030.         && ($this->isPreviewRequested($request)
  1031.             || $this->isPreviewApproved($request)
  1032.             || $this->isPreviewDeclined($request));
  1033.     }
  1034.     /**
  1035.      * Returns true if the preview has been declined.
  1036.      */
  1037.     final protected function isPreviewDeclined(Request $request): bool
  1038.     {
  1039.         return null !== $request->get('btn_preview_decline');
  1040.     }
  1041.     /**
  1042.      * @return \Traversable<UserInterface|string>
  1043.      */
  1044.     protected function getAclUsers(): \Traversable
  1045.     {
  1046.         if (!$this->container->has('sonata.admin.security.acl_user_manager')) {
  1047.             return new \ArrayIterator([]);
  1048.         }
  1049.         $aclUserManager $this->container->get('sonata.admin.security.acl_user_manager');
  1050.         \assert($aclUserManager instanceof AdminAclUserManagerInterface);
  1051.         $aclUsers $aclUserManager->findUsers();
  1052.         return \is_array($aclUsers) ? new \ArrayIterator($aclUsers) : $aclUsers;
  1053.     }
  1054.     /**
  1055.      * @return \Traversable<string>
  1056.      */
  1057.     protected function getAclRoles(): \Traversable
  1058.     {
  1059.         $aclRoles = [];
  1060.         $roleHierarchy $this->getParameter('security.role_hierarchy.roles');
  1061.         \assert(\is_array($roleHierarchy));
  1062.         $pool $this->container->get('sonata.admin.pool');
  1063.         \assert($pool instanceof Pool);
  1064.         foreach ($pool->getAdminServiceCodes() as $code) {
  1065.             try {
  1066.                 $admin $pool->getInstance($code);
  1067.             } catch (\Exception) {
  1068.                 continue;
  1069.             }
  1070.             $baseRole $admin->getSecurityHandler()->getBaseRole($admin);
  1071.             foreach ($admin->getSecurityInformation() as $role => $_permissions) {
  1072.                 $role sprintf($baseRole$role);
  1073.                 $aclRoles[] = $role;
  1074.             }
  1075.         }
  1076.         foreach ($roleHierarchy as $name => $roles) {
  1077.             $aclRoles[] = $name;
  1078.             $aclRoles array_merge($aclRoles$roles);
  1079.         }
  1080.         $aclRoles array_unique($aclRoles);
  1081.         return new \ArrayIterator($aclRoles);
  1082.     }
  1083.     /**
  1084.      * Validate CSRF token for action without form.
  1085.      *
  1086.      * @throws HttpException
  1087.      */
  1088.     final protected function validateCsrfToken(Request $requeststring $intention): void
  1089.     {
  1090.         if (!$this->container->has('security.csrf.token_manager')) {
  1091.             return;
  1092.         }
  1093.         $token $request->get('_sonata_csrf_token');
  1094.         $tokenManager $this->container->get('security.csrf.token_manager');
  1095.         \assert($tokenManager instanceof CsrfTokenManagerInterface);
  1096.         if (!$tokenManager->isTokenValid(new CsrfToken($intention$token))) {
  1097.             throw new HttpException(Response::HTTP_BAD_REQUEST'The csrf token is not valid, CSRF attack?');
  1098.         }
  1099.     }
  1100.     /**
  1101.      * Escape string for html output.
  1102.      */
  1103.     final protected function escapeHtml(string $s): string
  1104.     {
  1105.         return htmlspecialchars($s\ENT_QUOTES \ENT_SUBSTITUTE);
  1106.     }
  1107.     /**
  1108.      * Get CSRF token.
  1109.      */
  1110.     final protected function getCsrfToken(string $intention): ?string
  1111.     {
  1112.         if (!$this->container->has('security.csrf.token_manager')) {
  1113.             return null;
  1114.         }
  1115.         $tokenManager $this->container->get('security.csrf.token_manager');
  1116.         \assert($tokenManager instanceof CsrfTokenManagerInterface);
  1117.         return $tokenManager->getToken($intention)->getValue();
  1118.     }
  1119.     /**
  1120.      * This method can be overloaded in your custom CRUD controller.
  1121.      * It's called from createAction.
  1122.      *
  1123.      * @phpstan-param T $object
  1124.      */
  1125.     protected function preCreate(Request $requestobject $object): ?Response
  1126.     {
  1127.         return null;
  1128.     }
  1129.     /**
  1130.      * This method can be overloaded in your custom CRUD controller.
  1131.      * It's called from editAction.
  1132.      *
  1133.      * @phpstan-param T $object
  1134.      */
  1135.     protected function preEdit(Request $requestobject $object): ?Response
  1136.     {
  1137.         return null;
  1138.     }
  1139.     /**
  1140.      * This method can be overloaded in your custom CRUD controller.
  1141.      * It's called from deleteAction.
  1142.      *
  1143.      * @phpstan-param T $object
  1144.      */
  1145.     protected function preDelete(Request $requestobject $object): ?Response
  1146.     {
  1147.         return null;
  1148.     }
  1149.     /**
  1150.      * This method can be overloaded in your custom CRUD controller.
  1151.      * It's called from showAction.
  1152.      *
  1153.      * @phpstan-param T $object
  1154.      */
  1155.     protected function preShow(Request $requestobject $object): ?Response
  1156.     {
  1157.         return null;
  1158.     }
  1159.     /**
  1160.      * This method can be overloaded in your custom CRUD controller.
  1161.      * It's called from listAction.
  1162.      */
  1163.     protected function preList(Request $request): ?Response
  1164.     {
  1165.         return null;
  1166.     }
  1167.     /**
  1168.      * Translate a message id.
  1169.      *
  1170.      * @param mixed[] $parameters
  1171.      */
  1172.     final protected function trans(string $id, array $parameters = [], ?string $domain null, ?string $locale null): string
  1173.     {
  1174.         $domain ??= $this->admin->getTranslationDomain();
  1175.         $translator $this->container->get('translator');
  1176.         \assert($translator instanceof TranslatorInterface);
  1177.         return $translator->trans($id$parameters$domain$locale);
  1178.     }
  1179.     protected function handleXmlHttpRequestErrorResponse(Request $requestFormInterface $form): ?JsonResponse
  1180.     {
  1181.         if ([] === array_intersect(['application/json''*/*'], $request->getAcceptableContentTypes())) {
  1182.             return $this->renderJson([], Response::HTTP_NOT_ACCEPTABLE);
  1183.         }
  1184.         return $this->json(
  1185.             FormErrorIteratorToConstraintViolationList::transform($form->getErrors(true)),
  1186.             Response::HTTP_BAD_REQUEST
  1187.         );
  1188.     }
  1189.     /**
  1190.      * @phpstan-param T $object
  1191.      */
  1192.     protected function handleXmlHttpRequestSuccessResponse(Request $requestobject $object): JsonResponse
  1193.     {
  1194.         if ([] === array_intersect(['application/json''*/*'], $request->getAcceptableContentTypes())) {
  1195.             return $this->renderJson([], Response::HTTP_NOT_ACCEPTABLE);
  1196.         }
  1197.         return $this->renderJson([
  1198.             'result' => 'ok',
  1199.             'objectId' => $this->admin->getNormalizedIdentifier($object),
  1200.             'objectName' => $this->escapeHtml($this->admin->toString($object)),
  1201.         ]);
  1202.     }
  1203.     /**
  1204.      * @phpstan-return T|null
  1205.      */
  1206.     final protected function assertObjectExists(Request $requestbool $strict false): ?object
  1207.     {
  1208.         $admin $this->admin;
  1209.         $object null;
  1210.         while (null !== $admin) {
  1211.             $objectId $request->get($admin->getIdParameter());
  1212.             if (\is_string($objectId) || \is_int($objectId)) {
  1213.                 $adminObject $admin->getObject($objectId);
  1214.                 if (null === $adminObject) {
  1215.                     throw $this->createNotFoundException(sprintf(
  1216.                         'Unable to find %s object with id: %s.',
  1217.                         $admin->getClassnameLabel(),
  1218.                         $objectId
  1219.                     ));
  1220.                 } elseif (null === $object) {
  1221.                     /** @phpstan-var T $object */
  1222.                     $object $adminObject;
  1223.                 }
  1224.             } elseif ($strict || $admin !== $this->admin) {
  1225.                 throw $this->createNotFoundException(sprintf(
  1226.                     'Unable to find the %s object id of the admin "%s".',
  1227.                     $admin->getClassnameLabel(),
  1228.                     $admin::class
  1229.                 ));
  1230.             }
  1231.             $admin $admin->isChild() ? $admin->getParent() : null;
  1232.         }
  1233.         return $object;
  1234.     }
  1235.     /**
  1236.      * @return array{_tab?: string}
  1237.      */
  1238.     final protected function getSelectedTab(Request $request): array
  1239.     {
  1240.         return array_filter(['_tab' => (string) $request->request->get('_tab')]);
  1241.     }
  1242.     /**
  1243.      * Sets the admin form theme to form view. Used for compatibility between Symfony versions.
  1244.      *
  1245.      * @param string[]|null $theme
  1246.      */
  1247.     final protected function setFormTheme(FormView $formView, ?array $theme null): void
  1248.     {
  1249.         $twig $this->container->get('twig');
  1250.         \assert($twig instanceof Environment);
  1251.         $formRenderer $twig->getRuntime(FormRenderer::class);
  1252.         $formRenderer->setTheme($formView$theme);
  1253.     }
  1254.     /**
  1255.      * @phpstan-param T $object
  1256.      */
  1257.     final protected function checkParentChildAssociation(Request $requestobject $object): void
  1258.     {
  1259.         if (!$this->admin->isChild()) {
  1260.             return;
  1261.         }
  1262.         $parentAdmin $this->admin->getParent();
  1263.         $parentId $request->get($parentAdmin->getIdParameter());
  1264.         \assert(\is_string($parentId) || \is_int($parentId));
  1265.         $parentAdminObject $parentAdmin->getObject($parentId);
  1266.         if (null === $parentAdminObject) {
  1267.             throw new \RuntimeException(sprintf(
  1268.                 'No object was found in the admin "%s" for the id "%s".',
  1269.                 $parentAdmin::class,
  1270.                 $parentId
  1271.             ));
  1272.         }
  1273.         $parentAssociationMapping $this->admin->getParentAssociationMapping();
  1274.         if (null === $parentAssociationMapping) {
  1275.             return;
  1276.         }
  1277.         $propertyAccessor PropertyAccess::createPropertyAccessor();
  1278.         $propertyPath = new PropertyPath($parentAssociationMapping);
  1279.         $objectParent $propertyAccessor->getValue($object$propertyPath);
  1280.         // $objectParent may be an array or a Collection when the parent association is many to many.
  1281.         $parentObjectMatches $this->equalsOrContains($objectParent$parentAdminObject);
  1282.         if (!$parentObjectMatches) {
  1283.             throw new \RuntimeException(sprintf(
  1284.                 'There is no association between "%s" and "%s"',
  1285.                 $parentAdmin->toString($parentAdminObject),
  1286.                 $this->admin->toString($object)
  1287.             ));
  1288.         }
  1289.     }
  1290.     private function setTwigGlobal(string $namemixed $value): void
  1291.     {
  1292.         $twig $this->container->get('twig');
  1293.         \assert($twig instanceof Environment);
  1294.         try {
  1295.             $twig->addGlobal($name$value);
  1296.         } catch (\LogicException) {
  1297.             // Variable already set
  1298.         }
  1299.     }
  1300.     private function getBatchActionExecutable(string $action): callable
  1301.     {
  1302.         $batchActions $this->admin->getBatchActions();
  1303.         if (!\array_key_exists($action$batchActions)) {
  1304.             throw new \RuntimeException(sprintf('The `%s` batch action is not defined'$action));
  1305.         }
  1306.         $controller $batchActions[$action]['controller'] ?? sprintf(
  1307.             '%s::%s',
  1308.             $this->admin->getBaseControllerName(),
  1309.             sprintf('batchAction%s', (new UnicodeString($action))->camel()->title(true)->toString())
  1310.         );
  1311.         // This will throw an exception when called so we know if it's possible or not to call the controller.
  1312.         $exists false !== $this->container
  1313.             ->get('controller_resolver')
  1314.             ->getController(new Request([], [], ['_controller' => $controller]));
  1315.         if (!$exists) {
  1316.             throw new \RuntimeException(sprintf('Controller for action `%s` cannot be resolved'$action));
  1317.         }
  1318.         return function (ProxyQueryInterface $queryRequest $request) use ($controller): Response {
  1319.             $request->attributes->set('_controller'$controller);
  1320.             $request->attributes->set('query'$query);
  1321.             return $this->container->get('http_kernel')->handle($requestHttpKernelInterface::SUB_REQUEST);
  1322.         };
  1323.     }
  1324.     /**
  1325.      * Checks whether $needle is equal to $haystack or part of it.
  1326.      *
  1327.      * @param object|iterable<object> $haystack
  1328.      *
  1329.      * @return bool true when $haystack equals $needle or $haystack is iterable and contains $needle
  1330.      */
  1331.     private function equalsOrContains($haystackobject $needle): bool
  1332.     {
  1333.         if ($needle === $haystack) {
  1334.             return true;
  1335.         }
  1336.         if (is_iterable($haystack)) {
  1337.             foreach ($haystack as $haystackItem) {
  1338.                 if ($haystackItem === $needle) {
  1339.                     return true;
  1340.                 }
  1341.             }
  1342.         }
  1343.         return false;
  1344.     }
  1345. }