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

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