Checking POST data without a model in Silex / Symfony 2?

I am creating a RESTful application that will only serve json / xml data, and I chose Silex because I already know (a little) Symfony 2, and because it is small, I do not need Twig, etc.

No models, just old SQL queries using Doctrine dbal and serializer. Anyway, I have to check POST / PUT requests. How can this be done without using components and form models?

I mean that the POST data is an array. Can I check it (add restrictions) and how?

EDIT : Ok, now I found an interesting library, i.e. respect / validation . If necessary, it also uses sf restrictions. I ended up with something like this (early code: P), which I will use if there is nothing better:

$v = $app['validation.respect'];

$userConstraints = array(
    'last'     => $v::noWhitespace()->length(null, 255),
    'email'    => $v::email()->length(null, 255),
    'mobile'   => $v::regex('/^\+\d+$/'),
    'birthday' => $v::date('d-m-Y')->max(date('d-m-Y')),
);

// Generic function for request keys intersection
$converter = function(array $input, array $allowed)
{
    return array_intersect_key($input, array_flip($allowed));
};

// Convert POST params into an assoc. array where keys are only those allowed
$userConverter = function($fields, Request $request) use($converter) {

    $allowed = array('last', 'email', 'mobile', 'birthday');

    return $converter($request->request->all(), $allowed);
};

// Controller
$app->match('/user', function(Application $app, array $fields)
    use($userConstraints) {

    $results = array();

    foreach($fields as $key => $value)
        $results[] = $userConstraints[$key]->validate($value);

})->convert('fields', $userConverter);
+5
source share
3 answers

Well, you can check the array using the Symfony2 Validator component, for example

//namespace declaration    
use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Date;
use Symfony\Component\Validator\Constraints\NotBlank;
//....

 //validation snippet

  $constraint = new Collection(array(
    'email' => new Email(),
    'last'  => new NotBlank(),
    'birthday' => new Date(),
  ));

  $violationList = $this->get('validator')->validateValue($request->request->all(), $constraint);

  $errors = array();
  foreach ($violationList as $violation){
    $field = preg_replace('/\[|\]/', "", $violation->getPropertyPath());
    $error = $violation->getMessage();
    $errors[$field] = $error;
  }
+12
source

If you want to create an API with Symfony2 (similar to Silex), there is a good tutorial here: http://williamdurand.fr/2012/08/02/rest-apis-with-symfony2-the-right-way/

silex - form ( )! ! , , API ! http://www.slideshare.net/hhamon/silex-meets-soap-rest ( 42 )

.

, !

+3

This is well explained in the Symfony book here: http://symfony.com/doc/master/book/forms.html#adding-validation

+1
source

All Articles