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')),
);
$converter = function(array $input, array $allowed)
{
return array_intersect_key($input, array_flip($allowed));
};
$userConverter = function($fields, Request $request) use($converter) {
$allowed = array('last', 'email', 'mobile', 'birthday');
return $converter($request->request->all(), $allowed);
};
$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);
gremo source
share