renegare / aiv
API输入验证器(支持Silex)
v0.0.2
2014-06-12 17:01 UTC
Requires
- php: >=5.4.0
- symfony/validator: >=2.4,<2.6-dev
Requires (Dev)
- phpunit/phpunit: 3.7.*
- satooshi/php-coveralls: dev-master
- silex/silex: >=1.0
- symfony/browser-kit: >=2.3,<2.6-dev
- symfony/http-foundation: >=2.4,<2.6-dev
This package is not auto-updated.
Last update: 2024-09-24 01:17:44 UTC
README
要求
- PHP 5.4
- composer(建议使用最新版本)
安装
$ composer require renegare/aiv:dev-master
使用示例
Silex使用
<?php
$app = new \Silex\Application();
$app->register(new \AIV\Integration\SilexProvider, [
'aiv.validators' => [
'test-name' => [
'options' => [
'allow.extra.params' => true,
'allow.missing.params' => true
],
'params' => [
'name' => [
'not.blank',
[
'type' => 'length',
'options' => ['min' => 2, 'max' => 20]]],
'email' => ['not.blank', '%email.validator%'],
'password' => ['not.blank']]]]]);
$app['email.validator'] = $app->share(function() {
return new \Symfony\Component\Validator\Constraints\Email;
});
$app->post('/', function(Application $app) {
$apiValidator = $app['validator'];
if($apiValidator->hasErrors('test-name')) {
$errors = [];
foreach($apiValidator->getErrors('test-name') as $violation) {
$path = preg_replace('/[\[\]]/', '', $violation->getPropertyPath());
$errors[$path] = $violation->getMessage();
}
return sprintf('You have errors: <pre>%s</pre>', print_r($errors, true));
} else {
return sprintf('You sent me valid data:<br /><pre>%s</pre>', print_r($apiValidator->getData('test-name'), true));
}
});
$app->run();
JSON输入
典型的JSON Rest API应用程序从body中获取输入形式为json。在那里,默认输入处理程序将不起作用,因为它实际上在$_POST数组中查找。
在注册提供程序后简单地添加以下代码
$app['aiv.input'] = $this->share(function(){
new \AIV\Input\SymfonyRequest\JSONInput;
});
测试
查看仓库,并在顶级目录中运行以下命令(需要xdebug进行覆盖率测试)
$ composer update && vendor/bin/phpunit --coverage-text
路线图
- "Modelesque"类代表验证要求($instance_variables与注解)
幕后库
数据验证实际上由以下处理: Symfony/Validator组件