CsrfExtension.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  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 Symfony\Component\Form\Extension\Csrf;
  11. use Symfony\Component\Form\AbstractExtension;
  12. use Symfony\Component\Form\Exception\UnexpectedTypeException;
  13. use Symfony\Component\Form\Extension\Csrf\CsrfProvider\CsrfProviderAdapter;
  14. use Symfony\Component\Form\Extension\Csrf\CsrfProvider\CsrfProviderInterface;
  15. use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
  16. use Symfony\Component\Translation\TranslatorInterface;
  17. /**
  18. * This extension protects forms by using a CSRF token.
  19. *
  20. * @author Bernhard Schussek <bschussek@gmail.com>
  21. */
  22. class CsrfExtension extends AbstractExtension
  23. {
  24. private $tokenManager;
  25. private $translator;
  26. private $translationDomain;
  27. /**
  28. * @param CsrfTokenManagerInterface $tokenManager The CSRF token manager
  29. * @param TranslatorInterface $translator The translator for translating error messages
  30. * @param string|null $translationDomain The translation domain for translating
  31. */
  32. public function __construct($tokenManager, TranslatorInterface $translator = null, $translationDomain = null)
  33. {
  34. if ($tokenManager instanceof CsrfProviderInterface) {
  35. $tokenManager = new CsrfProviderAdapter($tokenManager);
  36. } elseif (!$tokenManager instanceof CsrfTokenManagerInterface) {
  37. throw new UnexpectedTypeException($tokenManager, 'CsrfProviderInterface or CsrfTokenManagerInterface');
  38. }
  39. $this->tokenManager = $tokenManager;
  40. $this->translator = $translator;
  41. $this->translationDomain = $translationDomain;
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. protected function loadTypeExtensions()
  47. {
  48. return array(
  49. new Type\FormTypeCsrfExtension($this->tokenManager, true, '_token', $this->translator, $this->translationDomain),
  50. );
  51. }
  52. }