title: Validation of POST data without a model in Silex / Symfony 2?
body: <p>I'm building a RESTful application that will serve only json/xml data and i've chosen Silex because i already know (a bit) Symfony 2 and because is small, i don't need Twig, etc...</p>
  
  <p>There are no models, just plain old SQL queries using Doctrine dbal, and the serializer. Anyway, i should validate POST/PUT requests. How this can be done without using form component and models?</p>
  
  <p>I mean POST data is an array. Can i validate it (adding constraints) and how?</p>
  
  <p><strong>EDIT</strong>: Ok, right now i've found an interesting library, that is <a href="http://packagist.org/packages/Respect/Validation" rel="nofollow">respect/validation</a>. It uses also sf constraints, if needed. I ended up with something like this (early code :P), that i will use if there is nothing better:</p>
  
  <pre class="lang-php prettyprint-override"><code>$v = $app['validation.respect'];
  
  $userConstraints = array(
      'last'     =&gt; $v::noWhitespace()-&gt;length(null, 255),
      'email'    =&gt; $v::email()-&gt;length(null, 255),
      'mobile'   =&gt; $v::regex('/^\+\d+$/'),
      'birthday' =&gt; $v::date('d-m-Y')-&gt;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-&gt;request-&gt;all(), $allowed);
  };
  
  // Controller
  $app-&gt;match('/user', function(Application $app, array $fields)
      use($userConstraints) {
  
      $results = array();
  
      foreach($fields as $key =&gt; $value)
          $results[] = $userConstraints[$key]-&gt;validate($value);
  
  })-&gt;convert('fields', $userConverter);
  </code></pre>