Skip to content

Instantly share code, notes, and snippets.

@SofHad
Created September 15, 2013 22:14
Show Gist options
  • Save SofHad/6574775 to your computer and use it in GitHub Desktop.
Save SofHad/6574775 to your computer and use it in GitHub Desktop.
Symfony OptionsResolver example of use case
<?php
namespace Demo\FormBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller ;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\HttpKernel\Exception\HttpException;
/**
* Controller.
*
*/
class DefaultController extends Controller {
/**
* Array of parameters accepted in the request, required parameter or not
*
* @var array
*/
protected $parameters = array(
'email' => true,
'firstName' => false
);
/**
* OptionsResolver example of use case
*
*/
public function indexAction() {
$resolver = new OptionsResolver();
$allowedValues = array(
'email' => array("sofiane.haddag@yahoo.fr", "mail@test.fr"),
);
$allowedTypes = array(
'firstName' => array("string", null),
);
$normalizer = array(
'firstName' => function ($options,$value) {
return ucfirst($value);
}) ;
$resolver
->setOptional(array_keys(array_filter($this->parameters, function ($val) {
return (false === $val);
})))
->setRequired(array_keys(array_filter($this->parameters, function ($val) {
return (true === $val);
})))
->setAllowedValues($allowedValues)
->setAllowedTypes($allowedTypes)
->setNormalizers( $normalizer );
try {
return $resolver->resolve($this->get('request')->query->all());
} catch (\Exception $e) {
throw new HttpException(400, 'Invalid parameters.');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment