在Silex/Symfony 2中验证没有模型的POST数据?

gre*_*emo 6 rest symfony silex

我正在构建一个只提供json/xml数据的RESTful应用程序,我选择了Silex,因为我已经知道(有点)Symfony 2,因为它很小,我不需要Twig等...

没有模型,只有使用Doctrine dbal的普通旧SQL查询和序列化程序.无论如何,我应该验证POST/PUT请求.如何在不使用表单组件和模型的情况下完成此操作?

我的意思是POST数据是一个数组.我可以验证它(添加约束)以及如何?

编辑:好的,现在我发现了一个有趣的库,这是尊重/验证.如果需要,它还使用sf约束.我最终得到了这样的东西(早期的代码:P),如果没有更好的东西,我将使用它:

$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);
Run Code Online (Sandbox Code Playgroud)

Mun*_*Das 13

那么你可以用Symfony2 Validator组件验证数组,例如

//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;
  }
Run Code Online (Sandbox Code Playgroud)