vendor/sonata-project/admin-bundle/src/Action/AppendFormFieldElementAction.php line 25

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\Action;
  12. use Sonata\AdminBundle\Admin\AdminHelper;
  13. use Sonata\AdminBundle\Exception\BadRequestParamHttpException;
  14. use Sonata\AdminBundle\Request\AdminFetcherInterface;
  15. use Symfony\Component\Form\FormRenderer;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpFoundation\Response;
  18. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  19. use Twig\Environment;
  20. final class AppendFormFieldElementAction
  21. {
  22.     public function __construct(
  23.         private Environment $twig,
  24.         private AdminFetcherInterface $adminFetcher,
  25.         private AdminHelper $helper,
  26.     ) {
  27.     }
  28.     /**
  29.      * @throws NotFoundHttpException
  30.      */
  31.     public function __invoke(Request $request): Response
  32.     {
  33.         try {
  34.             $admin $this->adminFetcher->get($request);
  35.         } catch (\InvalidArgumentException $e) {
  36.             throw new NotFoundHttpException($e->getMessage());
  37.         }
  38.         $objectId $request->get('objectId');
  39.         if (null === $objectId) {
  40.             $subject $admin->getNewInstance();
  41.         } elseif (\is_string($objectId) || \is_int($objectId)) {
  42.             $subject $admin->getObject($objectId);
  43.             if (null === $subject) {
  44.                 throw new NotFoundHttpException(\sprintf(
  45.                     'Unable to find the object id: %s, class: %s',
  46.                     $objectId,
  47.                     $admin->getClass()
  48.                 ));
  49.             }
  50.         } else {
  51.             throw new BadRequestParamHttpException('objectId', ['string''int''null'], $objectId);
  52.         }
  53.         $admin->setSubject($subject);
  54.         $elementId $request->get('elementId');
  55.         if (!\is_string($elementId)) {
  56.             throw new BadRequestParamHttpException('elementId''string'$elementId);
  57.         }
  58.         [, $form] = $this->helper->appendFormFieldElement($admin$subject$elementId);
  59.         $view $this->helper->getChildFormView($form->createView(), $elementId);
  60.         \assert(null !== $view);
  61.         // render the widget
  62.         $renderer $this->twig->getRuntime(FormRenderer::class);
  63.         $renderer->setTheme($view$admin->getFormTheme());
  64.         return new Response($renderer->searchAndRenderBlock($view'widget'));
  65.     }
  66. }