10000 [Form] Introduce validation events for forms by alcaeus · Pull Request #38479 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Form] Introduce validation events for forms #38479

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was di 10000 stributed with this source code.
*/

namespace Symfony\Component\Form\Extension\Validator\Event;

use Symfony\Component\Form\FormEvent;

/**
* This event is dispatched after validation completes.
*
* In this stage, the form will return a correct value to Form::isValid() and allow for
* further working with the form data.
*/
final class PostValidateEvent extends FormEvent
{
public function isFormValid(): bool
{
return $this->getForm()->isValid();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Form\Extension\Validator\Event;

use Symfony\Component\Form\FormEvent;

/**
* This event is dispatched before validation begins.
*
* In this stage the model and view data may have been denormalized. Otherwise the form
* is desynchronized because transformation failed during submission.
*
* It can be used to fetch data after denormalization.
*
* The event attaches the current view data. To know whether this is the renormalized data
* or the invalid request data, call Form::isSynchronized() first.
*/
final class PreValidateEvent extends FormEvent
{
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,12 @@

namespace Symfony\Component\Form\Extension\Validator\EventListener;

use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\Extension\Validator\Constraints\Form;
use Symfony\Component\Form\Extension\Validator\Event\PostValidateEvent;
use Symfony\Component\Form\Extension\Validator\Event\PreValidateEvent;
use Symfony\Component\Form\Extension\Validator\FormValidationEvents;
use Symfony\Component\Form\Extension\Validator\ViolationMapper\ViolationMapperInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
Expand All @@ -27,6 +31,8 @@ class ValidationListener implements EventSubscriberInterface

private $violationMapper;

private $eventDispatcher;

/**
* {@inheritdoc}
*/
Expand All @@ -35,17 +41,27 @@ public static function getSubscribedEvents()
return [FormEvents::POST_SUBMIT => 'validateForm'];
}

public function __construct(ValidatorInterface $validator, ViolationMapperInterface $violationMapper)
public function __construct(ValidatorInterface $validator, ViolationMapperInterface $violationMapper, ?EventDispatcherInterface $eventDispatcher = null)
{
$this->validator = $validator;
$this->violationMapper = $violationMapper;

if (!$eventDispatcher) {
@trigger_error(sprintf('The "$eventDispatcher" argument to the "%s" constructor will be required in Symfony 6.0.', self::class));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now it is recommended to use the trigger_deprecation function of the symfony/deprecation-contracts package

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That tells you how old this is and I'm not really staying on top of this. If someone else would like to take it over, please do!

}

$this->eventDispatcher = $eventDispatcher;
}

public function validateForm(FormEvent $event)
{
$form = $event->getForm();

if ($form->isRoot()) {
if ($this->eventDispatcher) {
$this->eventDispatcher->dispatch(new PreValidateEvent($event->getForm(), $event->getData()), FormValidationEvents::PRE_VALIDATE);
}

// Form groups are validated internally (FormValidator). Here we don't set groups as they are retrieved into the validator.
foreach ($this->validator->validate($form) as $violation) {
// Allow the "invalid" constraint to be put onto
Expand All @@ -54,6 +70,10 @@ public function validateForm(FormEvent $event)

$this->violationMapper->mapViolation($violation, $form, $allowNonSynchronized);
}

if ($this->eventDispatcher) {
$this->eventDispatcher->dispatch(new PostValidateEvent($event->getForm(), $event->getData()), FormValidationEvents::POST_VALIDATE);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Form\Extension\Validator;

final class FormValidationEvents
{
/**
* @see Event\PreValidateEvent
* @Event(Event\PreValidateEvent::class)
*/
const PRE_VALIDATE = 'form.pre_validate';

/**
* This event is dispatched after validation completes.
*
* In this stage, the form will return a correct value to Form::isValid() and allow for
* further working with the form data.
*
* @see Event\PostValidateEvent
* @Event(Event\PostValidateEvent::class)
*/
const POST_VALIDATE = 'form.post_validate';
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Symfony\Component\Form\Extension\Core\DataMapper\DataMapper;
use Symfony\Component\Form\Extension\Validator\Constraints\Form as FormConstraint;
use Symfony\Component\Form\Extension\Validator\EventListener\ValidationListener;
use Symfony\Component\Form\Extension\Validator\FormValidationEvents;
use Symfony\Component\Form\Extension\Validator\ViolationMapper\ViolationMapper;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormBuilder;
Expand Down Expand Up @@ -67,21 +68,26 @@ protected function setUp(): void
$this->dispatcher = new EventDispatcher();
$this->factory = (new FormFactoryBuilder())->getFormFactory();
$this->validator = Validation::createValidator();
$this->listener = new ValidationListener($this->validator, new ViolationMapper());
$this->listener = new ValidationListener($this->validator, new ViolationMapper(), $this->dispatcher);
$this->message = 'Message';
$this->messageTemplate = 'Message template';
$this->params = ['foo' => 'bar'];
}

private function createForm($name = '', $compound = false)
private function createForm($name = '', $compound = false, ?object $listener = null)
{
$config = new FormBuilder($name, null, new EventDispatcher(), (new FormFactoryBuilder())->getFormFactory());
$config = new FormBuilder($name, null, $this->dispatcher, (new FormFactoryBuilder())->getFormFactory());
$config->setCompound($compound);

if ($compound) {
$config->setDataMapper(new DataMapper());
}

if ($listener) {
$config->addEventListener(FormValidationEvents::PRE_VALIDATE, [$listener, 'preValidate']);
$config->addEventListener(FormValidationEvents::POST_VALIDATE, [$listener, 'postValidate']);
}

return new Form($config);
}

Expand Down Expand Up @@ -136,6 +142,32 @@ public function testValidateWithEmptyViolationList()

$this->assertTrue($form->isValid());
}

public function testEventsAreDispatched()
{
$data = ['foo' => 'bar'];

$mock = $this->getMockBuilder('\stdClass')
->setMethods(['preValidate', 'postValidate'])
->getMock();
$mock->expects($this->once())
->method('preValidate')
->with($this->callback(function ($event) use ($data) {
return $data === $event->getData();
}));
$mock->expects($this->once())
->method('postValidate')
->with($this->callback(function ($event) use ($data) {
return $data === $event->getData();
}));

$form = $this->createForm('', false, $mock);
$form->submit($data);

$this->listener->validateForm(new FormEvent($form, $data));

$this->assertTrue($form->isValid());
}
}

class SubmittedNotSynchronizedForm extends Form
Expand Down
0