Commit c0745457 authored by Dave Marshall's avatar Dave Marshall

The form csrf extension should use the translator if available

Fixes #896
parent 68f9b2a9
......@@ -55,9 +55,17 @@ class FormServiceProvider implements ServiceProviderInterface
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 @@ namespace Silex\Tests\Provider;
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 @@ class FormServiceProviderTest extends \PHPUnit_Framework_TestCase
$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 @@ class DummyFormTypeExtension extends AbstractTypeExtension
$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);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment