Created
September 15, 2013 22:14
-
-
Save SofHad/6574775 to your computer and use it in GitHub Desktop.
Symfony OptionsResolver example of use case
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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("[email protected]", "[email protected]"), | |
); | |
$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