This repository has been archived by the owner. It is now read-only.
Permalink
Browse files

The form csrf extension should use the translator if available

Fixes #896
  • Loading branch information...
davedevelopment committed Jan 29, 2014
1 parent 68f9b2a commit c07454574b4b1315a64e5a12b69927704a359355
@@ -55,9 +55,17 @@ public function register(Application $app)
return array();
});
$app['form.extension.csrf'] = $app->share(function ($app) {
if (isset($app['translator'])) {
return new CsrfExtension($app['form.csrf_provider'], $app['translator']);
}
return new CsrfExtension($app['form.csrf_provider']);
});
$app['form.extensions'] = $app->share(function ($app) {
$extensions = array(
new CsrfExtension($app['form.csrf_provider']),
$app['form.extension.csrf'],
new HttpFoundationExtension(),
);
@@ -13,8 +13,11 @@
use Silex\Application;
use Silex\Provider\FormServiceProvider;
use Silex\Provider\TranslationServiceProvider;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Csrf\CsrfProvider\CsrfProviderInterface;
use Symfony\Component\Form\FormTypeGuesserChain;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class FormServiceProviderTest extends \PHPUnit_Framework_TestCase
@@ -59,6 +62,36 @@ public function testFormServiceProviderWillLoadTypeGuessers()
$this->assertInstanceOf('Symfony\Component\Form\FormFactory', $app['form.factory']);
}
public function testFormServiceProviderWillUseTranslatorIfAvailable()
{
$app = new Application();
$app->register(new FormServiceProvider());
$app->register(new TranslationServiceProvider());
$app['translator.domains'] = array(
'messages' => array(
'de' => array (
'The CSRF token is invalid. Please try to resubmit the form.' => 'German translation',
)
)
);
$app['locale'] = 'de';
$app['form.csrf_provider'] = $app->share(function () {
return new FakeCsrfProvider();
});
$form = $app['form.factory']->createBuilder('form', array())
->getForm();
$form->handleRequest($req = Request::create('/', 'POST', array('form' => array(
'_token' => 'the wrong token'
))));
$this->assertFalse($form->isValid());
$this->assertContains('ERROR: German translation', $form->getErrorsAsString());
}
}
class DummyFormTypeExtension extends AbstractTypeExtension
@@ -73,3 +106,16 @@ public function setDefaultOptions(OptionsResolverInterface $resolver)
$resolver->setOptional(array('image_path'));
}
}
class FakeCsrfProvider implements CsrfProviderInterface
{
public function generateCsrfToken($intention)
{
return $intention.'123';
}
public function isCsrfTokenValid($intention, $token)
{
return $token === $this->generateCsrfToken($intention);
}
}

0 comments on commit c074545

Please sign in to comment.