vendor/sonata-project/admin-bundle/src/Admin/Extension/LockExtension.php line 29

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\Admin\Extension;
  12. use Sonata\AdminBundle\Admin\AbstractAdminExtension;
  13. use Sonata\AdminBundle\Admin\AdminInterface;
  14. use Sonata\AdminBundle\Form\FormMapper;
  15. use Sonata\AdminBundle\Model\LockInterface;
  16. use Symfony\Component\Form\Extension\Core\Type\HiddenType;
  17. use Symfony\Component\Form\FormEvent;
  18. use Symfony\Component\Form\FormEvents;
  19. /**
  20.  * @author Emmanuel Vella <vella.emmanuel@gmail.com>
  21.  *
  22.  * @phpstan-extends AbstractAdminExtension<object>
  23.  */
  24. final class LockExtension extends AbstractAdminExtension
  25. {
  26.     private string $fieldName '_lock_version';
  27.     public function configureFormFields(FormMapper $form): void
  28.     {
  29.         $admin $form->getAdmin();
  30.         $formBuilder $form->getFormBuilder();
  31.         $formBuilder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($admin): void {
  32.             $data $event->getData();
  33.             $form $event->getForm();
  34.             if (!\is_object($data) || null !== $form->getParent()) {
  35.                 return;
  36.             }
  37.             $modelManager $admin->getModelManager();
  38.             if (!$modelManager instanceof LockInterface) {
  39.                 return;
  40.             }
  41.             if (null === $lockVersion $modelManager->getLockVersion($data)) {
  42.                 return;
  43.             }
  44.             $form->add($this->fieldNameHiddenType::class, [
  45.                 'mapped' => false,
  46.                 'data' => $lockVersion,
  47.             ]);
  48.         });
  49.     }
  50.     public function preUpdate(AdminInterface $adminobject $object): void
  51.     {
  52.         if (!$admin->hasRequest()) {
  53.             return;
  54.         }
  55.         $data $admin->getRequest()->get($admin->getUniqId());
  56.         if (!\is_array($data)) {
  57.             return;
  58.         }
  59.         if (!isset($data[$this->fieldName])) {
  60.             return;
  61.         }
  62.         $modelManager $admin->getModelManager();
  63.         if (!$modelManager instanceof LockInterface) {
  64.             return;
  65.         }
  66.         $modelManager->lock($object, (int) $data[$this->fieldName]);
  67.     }
  68. }