4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Form\Extension\Csrf\EventListener
;
14 use Symfony\Component\EventDispatcher\EventSubscriberInterface
;
15 use Symfony\Component\Form\FormEvents
;
16 use Symfony\Component\Form\FormError
;
17 use Symfony\Component\Form\FormEvent
;
18 use Symfony\Component\Form\Extension\Csrf\CsrfProvider\CsrfProviderInterface
;
19 use Symfony\Component\Translation\TranslatorInterface
;
22 * @author Bernhard Schussek <bschussek@gmail.com>
24 class CsrfValidationListener
implements EventSubscriberInterface
27 * The name of the CSRF field
33 * The provider for generating and validating CSRF tokens
34 * @var CsrfProviderInterface
36 private $csrfProvider;
39 * A text mentioning the intention of the CSRF token
41 * Validation of the token will only succeed if it was generated in the
42 * same session and with the same intention.
49 * The message displayed in case of an error.
52 private $errorMessage;
55 * @var TranslatorInterface
62 private $translationDomain;
64 public static function getSubscribedEvents()
67 FormEvents
::PRE_SUBMIT
=> 'preSubmit',
71 public function __construct($fieldName, CsrfProviderInterface
$csrfProvider, $intention, $errorMessage, TranslatorInterface
$translator = null, $translationDomain = null)
73 $this->fieldName
= $fieldName;
74 $this->csrfProvider
= $csrfProvider;
75 $this->intention
= $intention;
76 $this->errorMessage
= $errorMessage;
77 $this->translator
= $translator;
78 $this->translationDomain
= $translationDomain;
81 public function preSubmit(FormEvent
$event)
83 $form = $event->getForm();
84 $data = $event->getData();
86 if ($form->isRoot() && $form->getConfig()->getOption('compound')) {
87 if (!isset($data[$this->fieldName
]) || !$this->csrfProvider
->isCsrfTokenValid($this->intention
, $data[$this->fieldName
])) {
88 $errorMessage = $this->errorMessage
;
90 if (null !== $this->translator
) {
91 $errorMessage = $this->translator
->trans($errorMessage, array(), $this->translationDomain
);
94 $form->addError(new FormError($errorMessage));
97 if (is_array($data)) {
98 unset($data[$this->fieldName
]);
102 $event->setData($data);
106 * Alias of {@link preSubmit()}.
108 * @deprecated Deprecated since version 2.3, to be removed in 3.0. Use
109 * {@link preSubmit()} instead.
111 public function preBind(FormEvent
$event)
113 $this->preSubmit($event);