LockExtension.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /*
  3. * This file is part of the Sonata Project package.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Sonata\AdminBundle\Admin\Extension;
  11. use Sonata\AdminBundle\Admin\AbstractAdminExtension;
  12. use Sonata\AdminBundle\Admin\AdminInterface;
  13. use Sonata\AdminBundle\Form\FormMapper;
  14. use Sonata\AdminBundle\Model\LockInterface;
  15. use Symfony\Component\Form\FormEvent;
  16. use Symfony\Component\Form\FormEvents;
  17. /**
  18. * @author Emmanuel Vella <vella.emmanuel@gmail.com>
  19. */
  20. class LockExtension extends AbstractAdminExtension
  21. {
  22. /**
  23. * @var string
  24. */
  25. protected $fieldName = '_lock_version';
  26. /**
  27. * {@inheritdoc}
  28. */
  29. public function configureFormFields(FormMapper $form)
  30. {
  31. $admin = $form->getAdmin();
  32. $formBuilder = $form->getFormBuilder();
  33. // PHP 5.3 BC
  34. $fieldName = $this->fieldName;
  35. $formBuilder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($admin, $fieldName) {
  36. $data = $event->getData();
  37. $form = $event->getForm();
  38. if (null === $data || $form->getParent()) {
  39. return;
  40. }
  41. $modelManager = $admin->getModelManager();
  42. if (!$modelManager instanceof LockInterface) {
  43. return;
  44. }
  45. if (null === $lockVersion = $modelManager->getLockVersion($data)) {
  46. return;
  47. }
  48. $form->add(
  49. $fieldName,
  50. // NEXT_MAJOR: remove the check and add the FQCN
  51. method_exists('Symfony\Component\Form\AbstractType', 'getBlockPrefix')
  52. ? 'Symfony\Component\Form\Extension\Core\Type\HiddenType'
  53. : 'hidden',
  54. array(
  55. 'mapped' => false,
  56. 'data' => $lockVersion,
  57. )
  58. );
  59. });
  60. }
  61. /**
  62. * {@inheritdoc}
  63. */
  64. public function preUpdate(AdminInterface $admin, $object)
  65. {
  66. if (!$admin->hasRequest() || !$data = $admin->getRequest()->get($admin->getUniqid())) {
  67. return;
  68. }
  69. if (!isset($data[$this->fieldName])) {
  70. return;
  71. }
  72. $modelManager = $admin->getModelManager();
  73. if (!$modelManager instanceof LockInterface) {
  74. return;
  75. }
  76. $modelManager->lock($object, $data[$this->fieldName]);
  77. }
  78. }