Skip to content

Commit 6840409

Browse files
committed
merge master feature to php5 branch
1 parent ceed770 commit 6840409

18 files changed

+836
-313
lines changed

README.md

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
- 支持基本的数组检查,数组的子级值检查
1616
- 方便的获取错误信息,验证后的安全数据获取
1717
- 已经内置了40多个常用的验证器[内置验证器](#built-in-validators)
18-
- 规则设置参考自 yii 的。部分规则参考自 laravel
18+
- 规则设置参考 yii. 部分规则参考自 laravel, Respect/Validation
1919
- 新增了独立的过滤器 `Inhere\Validate\Filter\Filtration` 用于数据过滤
2020

2121
支持两种规则配置方式:
@@ -56,9 +56,9 @@ e.g
5656

5757
- 使用 composer 命令
5858

59-
```bash
60-
composer require inhere/php-validate
61-
// composer require inhere/php-validate ^version // 指定版本
59+
```php
60+
composer require inhere/php-validate
61+
// composer require inhere/php-validate ^2.2
6262
```
6363

6464
- 使用 composer.json
@@ -97,14 +97,14 @@ class PageRequest extends Validation
9797
{
9898
return [
9999
['tagId,title,userId,freeTime', 'required'],
100-
['tagId', 'size', 'min'=>4, 'max'=>567], // 4<= tagId <=567
101-
['title', 'min', 40],
100+
['tagId', 'size', 'min'=>4, 'max'=>567, 'filter' => 'int'], // 4<= tagId <=567
101+
['title', 'min', 40, 'filter' => 'trim'],
102102
['freeTime', 'number'],
103103
['tagId', 'number', 'when' => function($data) {
104104
return isset($data['status']) && $data['status'] > 2;
105105
}],
106-
['userId', 'number', 'on' => 'scene1' ],
107-
['username', 'string', 'on' => 'scene2' ],
106+
['userId', 'number', 'on' => 'scene1', 'filter' => 'int'],
107+
['username', 'string', 'on' => 'scene2', 'filter' => 'trim'],
108108
['username', 'regexp' ,'/^[a-z]\w{2,12}$/'],
109109
['title', 'customValidator', 'msg' => '{attr} error msg!' ], // 指定当前规则的消息
110110
['status', function($status) { // 直接使用闭包验证
@@ -376,8 +376,7 @@ $v = Validation::make($_POST,[
376376
{
377377
return [
378378
['title', 'required' ],
379-
['tagId', 'number', 'when' => function($data)
380-
{
379+
['tagId', 'number', 'when' => function($data) {
381380
return isset($data['status']) && $data['status'] > 2;
382381
}],
383382
];
@@ -514,6 +513,7 @@ public function isFail() // hasError() 的别名方法
514513
public function fail() // hasError() 的别名方法
515514
516515
// 成功通过验证
516+
public function ok()
517517
public function passed()
518518
public function isPassed() // passed() 的别名方法
519519
```
@@ -597,17 +597,19 @@ public function get(string $key, $default = null)
597597

598598
过滤器 | 说明 | 示例
599599
-------|-------------|------------
600-
`int/integer` | 过滤非法字符并转换为`int`类型 | `['userId', 'number', 'filter' => 'int'],`
600+
`abs` | 返回绝对值 | `['field', 'int', 'filter' => 'abs'],`
601+
`int/integer` | 过滤非法字符并转换为`int`类型 **支持数组** | `['userId', 'number', 'filter' => 'int'],`
601602
`float` | 过滤非法字符,保留`float`格式的数据 | `['price', 'float', 'filter' => 'float'],`
602603
`string` | 过滤非法字符并转换为`string`类型 | `['userId', 'number', 'filter' => 'string'],`
603604
`trim` | 去除首尾空白字符,支持数组。 | `['username', 'min', 4, 'filter' => 'trim'],`
605+
`nl2br` | 转换 `\n` `\r\n` `\r``<br/>` | `['content', 'string', 'filter' => 'nl2br'],`
604606
`lower/lowercase` | 字符串转换为小写 | `['description', 'string', 'filter' => 'lowercase'],`
605607
`upper/uppercase` | 字符串转换为大写 | `['title', 'string', 'filter' => 'uppercase'],`
606608
`snake/snakeCase` | 字符串转换为蛇形风格 | `['title', 'string', 'filter' => 'snakeCase'],`
607609
`camel/camelCase` | 字符串转换为驼峰风格 | `['title', 'string', 'filter' => 'camelCase'],`
608610
`timestamp/strToTime` | 字符串日期转换时间戳 | `['pulishedAt', 'number', 'filter' => 'strToTime'],`
609-
`abs` | 返回绝对值 | `['field', 'int', 'filter' => 'abs'],`
610611
`url` | URL 过滤,移除所有不符合 URL 的字符 | `['field', 'url', 'filter' => 'url'],`
612+
`str2list/str2array` | 字符串转数组 `'tag0,tag1' -> ['tag0', 'tag1']` | `['tags', 'strList', 'filter' => 'str2array'],`
611613
`email` | email 过滤,移除所有不符合 email 的字符 | `['field', 'email', 'filter' => 'email'],`
612614
`encoded` | 去除 URL 编码不需要的字符,与 `urlencode()` 函数很类似 | `['imgUrl', 'url', 'filter' => 'encoded'],`
613615
`clearTags/stripTags` | 相当于使用 `strip_tags()` | `['content', 'string', 'filter' => 'clearTags'],`
@@ -623,11 +625,11 @@ public function get(string $key, $default = null)
623625
624626
验证器 | 说明 | 规则示例
625627
----------|-------------|------------
626-
`int/integer` | 验证是否是 int | `['userId', 'int']`
627-
`num/number` | 验证是否是 number | `['userId', 'number']`
628+
`int/integer` | 验证是否是 int **支持范围检查** | `['userId', 'int']` `['userId', 'int', 'min'=>4, 'max'=>16]`
629+
`num/number` | 验证是否是 number **支持范围检查** | `['userId', 'number']` `['userId', 'number', 'min'=>4, 'max'=>16]`
628630
`bool/boolean` | 验证是否是 bool | `['open', 'bool']`
629631
`float` | 验证是否是 float | `['price', 'float']`
630-
`string` | 验证是否是 string. 支持长度检查 | `['name', 'string']`, `['name', 'string', 'min'=>4, 'max'=>16]`
632+
`string` | 验证是否是 string. **支持长度检查** | `['name', 'string']`, `['name', 'string', 'min'=>4, 'max'=>16]`
631633
`url` | 验证是否是 url | `['myUrl', 'url']`
632634
`email` | 验证是否是 email | `['userEmail', 'email']`
633635
`alpha` | 验证值是否仅包含字母字符 | `['name', 'alpha']`
@@ -636,14 +638,18 @@ public function get(string $key, $default = null)
636638
`isMap` | 验证值是否是一个非自然数组 map (key - value 形式的) | `['goods', 'isMap']`
637639
`isList` | 验证值是否是一个自然数组 list (key是从0自然增长的) | `['tags', 'isList']`
638640
`isArray` | 验证是否是数组 | `['goods', 'isArray']`
641+
`hasKey` | 验证数组存在给定的key(s) | `['goods', 'hasKey', 'pear']` `['goods', 'hasKey', ['pear', 'banana']]`
639642
`intList` | 验证字段值是否是一个 int list | `['tagIds', 'intList']`
640643
`numList` | 验证字段值是否是一个 number list | `['tagIds', 'numList']`
641644
`strList` | 验证字段值是否是一个 string list | `['tags', 'strList']`
642645
`min` | 最小边界值验证 | `['title', 'min', 40]`
643646
`max` | 最大边界值验证 | `['title', 'max', 40]`
644647
`size/range/between` | 验证大小范围, 可以支持验证 `int`, `string`, `array` 数据类型 | `['tagId', 'size', 'min'=>4, 'max'=>567]`
645648
`length` | 长度验证( 跟 `size`差不多, 但只能验证 `string`, `array` 的长度 | `['username', 'length', 'min' => 5, 'max' => 20]`
646-
`in/enum` | 枚举验证 | `['status', 'in', [1,2,3]`
649+
`fixedSize/fixedLength` | 固定的长度/大小 | `['field', 'fixedSize', 12]`
650+
`startWith` | 值(`string/array`)是以给定的字符串开始 | `['field', 'startWith', 'hell']`
651+
`endWith` | 值(`string/array`)是以给定的字符串结尾 | `['field', 'endWith', 'world']`
652+
`in/enum` | 枚举验证 | `['status', 'in', [1,2,3]]`
647653
`notIn` | 枚举验证 | `['status', 'notIn', [4,5,6]]`
648654
`mustBe` | 必须是等于给定值 | `['status', 'mustBe', 1]`
649655
`notBe` | 不能等于给定值 | `['status', 'notBe', 0]`
@@ -663,12 +669,13 @@ public function get(string $key, $default = null)
663669
`beforeOrEqualDate` | 字段值必须是小于或等于给定日期的值 | `['publishedAt', 'beforeOrEqualDate', '2017-05-12']`
664670
`afterOrEqualDate` | 字段值必须是大于或等于给定日期的值 | `['publishedAt', 'afterOrEqualDate', '2017-05-12']`
665671
`afterDate` | 验证字段值必须是给定日期之前的值 | `['publishedAt', 'afterDate', '2017-05-12']`
666-
`json` | 验证是否是json字符串 | `['goods', 'json']`
672+
`json` | 验证是否是json字符串(默认严格验证,必须以`{` `[` 开始) | `['goods', 'json']` `['somedata', 'json', false]` - 非严格,普通字符串`eg 'test'`也会通过
667673
`file` | 验证是否是上传的文件 | `['upFile', 'file']`
668674
`image` | 验证是否是上传的图片文件 | `['avatar', 'image']`, 限定后缀名 `['avatar', 'image', 'jpg,png']`
669675
`ip` | 验证是否是 IP | `['ipAddr', 'ip']`
670676
`ipv4` | 验证是否是 IPv4 | `['ipAddr', 'ipv4']`
671677
`ipv6` | 验证是否是 IPv6 | `['ipAddr', 'ipv6']`
678+
`macAddress` | 验证是否是 mac Address | `['field', 'macAddress']`
672679
`md5` | 验证是否是 md5 格式的字符串 | `['passwd', 'md5']`
673680
`sha1` | 验证是否是 sha1 格式的字符串 | `['passwd', 'sha1']`
674681
`color` | 验证是否是html color | `['backgroundColor', 'color']`

examples/DataModel.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ class DataModel
1111

1212
protected $data = [];
1313

14+
protected $db;
15+
1416
/**
1517
* @param array $data
1618
* @return $this
@@ -21,4 +23,13 @@ public function setData($data)
2123

2224
return $this;
2325
}
26+
27+
public function create()
28+
{
29+
if ($this->validate()->fail()) {
30+
return false;
31+
}
32+
33+
return $this->db->insert($this->getSafeData());
34+
}
2435
}

api.md renamed to examples/api.md

File renamed without changes.

examples/filter.php

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,31 @@
11
<?php
2-
/**
3-
* Created by PhpStorm.
4-
* User: inhere
5-
* Date: 2017-11-24
6-
* Time: 18:13
7-
*/
2+
3+
require __DIR__ . '/simple-loader.php';
4+
5+
$data = [
6+
'name' => ' tom ',
7+
'status' => ' 23 ',
8+
'word' => 'word',
9+
'toLower' => 'WORD',
10+
'title' => 'helloWorld',
11+
];
12+
13+
$rules = [
14+
['name', 'string|trim'],
15+
['status', 'trim|int'],
16+
['word', 'string|trim|upper'],
17+
['toLower', 'lower'],
18+
['title', [
19+
'string',
20+
'snake' => ['-'],
21+
'ucfirst',
22+
]],
23+
];
24+
25+
echo "------------- raw data: -------------\n";
26+
var_dump($data);
27+
28+
$cleaned = \Inhere\Validate\Filter\Filtration::make($data, $rules)->filtering();
29+
30+
echo "------------- cleaned data: -------------\n";
31+
var_dump($cleaned);

examples/help.md

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# help
2+
3+
4+
```php
5+
6+
/**
7+
* @link http://php.net/manual/zh/function.filter-input.php
8+
* @param int $type INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV
9+
* @param $varName
10+
* @param array $filter 过滤/验证器 {@link http://php.net/manual/zh/filter.filters.php}
11+
* @param array $options 一个选项的关联数组,或者按位区分的标示。
12+
* 如果过滤器接受选项,可以通过数组的 "flags" 位去提供这些标示。
13+
* 如果成功的话返回所请求的变量。
14+
* 如果成功的话返回所请求的变量。
15+
* 如果过滤失败则返回 FALSE ,
16+
* 如果 varName 不存在的话则返回 NULL 。
17+
* 如果标示 FILTER_NULL_ON_FAILURE 被使用了,那么当变量不存在时返回 FALSE ,当过滤失败时返回 NULL 。
18+
*/
19+
public static function input($type, $varName, $filter, array $options = [])
20+
{
21+
}
22+
23+
public static function multi(array $data, array $filters = [])
24+
{
25+
}
26+
27+
/**
28+
* @link http://php.net/manual/zh/function.filter-input-array.php
29+
* 检查(验证/过滤)输入数据中的多个变量名 like filter_input_array()
30+
* 当需要获取很多变量却不想重复调用 filter_input()时很有用。
31+
* @param int $type One of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV. 要检查的输入数据
32+
* @param mixed $definition 一个定义参数的数组。
33+
* 一个有效的键必须是一个包含变量名的string,
34+
* 一个有效的值要么是一个filter type,或者是一个array 指明了过滤器、标示和选项。
35+
* 如果值是一个数组,那么它的有效的键可以是 :
36+
* filter, 用于指明 filter type,
37+
* flags 用于指明任何想要用于过滤器的标示,
38+
* options 用于指明任何想要用于过滤器的选项。
39+
* 参考下面的例子来更好的理解这段说明。
40+
* @param bool $addEmpty 在返回值中添加 NULL 作为不存在的键。
41+
* 如果成功的话返回一个所请求的变量的数组,
42+
* 如果失败的话返回 FALSE 。
43+
* 对于数组的值,
44+
* 如果过滤失败则返回 FALSE ,
45+
* 如果 variable_name 不存在的话则返回 NULL 。
46+
* 如果标示 FILTER_NULL_ON_FAILURE 被使用了,那么当变量不存在时返回 FALSE ,当过滤失败时返回 NULL 。
47+
*/
48+
public static function inputMulti($type, $definition, $addEmpty = true)
49+
{
50+
}
51+
52+
/**
53+
* 检查变量名是否存在
54+
* @param int $type One of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV. 要检查的输入数据
55+
* @param string $varName Name of a variable to check. 要检查的变量名
56+
*/
57+
public static function inputHasVar($type, $varName)
58+
{
59+
}
60+
```

src/AbstractValidation.php

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,13 @@ abstract class AbstractValidation implements ValidationInterface
4040
* @throws \InvalidArgumentException
4141
* @throws \RuntimeException
4242
*/
43-
public function __construct(array $data = [], array $rules = [], array $translates = [], $scene = '', $startValidate = false)
44-
{
43+
public function __construct(
44+
array $data = [],
45+
array $rules = [],
46+
array $translates = [],
47+
$scene = '',
48+
$startValidate = false
49+
) {
4550
$this->data = $data;
4651
$this->setRules($rules)->setScene($scene)->setTranslates($translates);
4752
if ($startValidate) {
@@ -59,8 +64,28 @@ public function __construct(array $data = [], array $rules = [], array $translat
5964
* @throws \InvalidArgumentException
6065
* @throws \RuntimeException
6166
*/
62-
public static function make(array $data, array $rules = [], array $translates = [], $scene = '', $startValidate = false)
63-
{
67+
public static function make(
68+
array $data,
69+
array $rules = [],
70+
array $translates = [],
71+
$scene = '',
72+
$startValidate = false
73+
) {
6474
return new static($data, $rules, $translates, $scene, $startValidate);
6575
}
76+
77+
/**
78+
* 创建并且立即开始验证
79+
* @param array $data
80+
* @param array $rules
81+
* @param array $translates
82+
* @param string $scene
83+
* @return static
84+
* @throws \InvalidArgumentException
85+
* @throws \RuntimeException
86+
*/
87+
public static function makeAndValidate(array $data, array $rules = [], array $translates = [], $scene = '')
88+
{
89+
return new static($data, $rules, $translates, $scene, true);
90+
}
6691
}

src/FieldValidation.php

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99

1010
namespace Inhere\Validate;
1111

12+
use Inhere\Validate\Utils\Helper;
13+
1214
/**
1315
* Class FieldValidation
1416
* - one field to many rules. like Laravel framework
@@ -50,13 +52,12 @@ protected function collectRules()
5052
if (!$scene) {
5153
continue;
5254
}
53-
$sceneList = \is_string($rule['on']) ? array_map('trim', explode(',', $rule['on'])) : (array)$rule['on'];
55+
$sceneList = \is_string($rule['on']) ? Helper::explode($rule['on']) : (array)$rule['on'];
5456
if (!\in_array($scene, $sceneList, true)) {
5557
continue;
5658
}
5759
unset($rule['on']);
5860
}
59-
6061
$this->_usedRules[] = $rule;
6162
$field = array_shift($rule);
6263
if (\is_object($rule[0])) {
@@ -70,8 +71,6 @@ protected function collectRules()
7071
}
7172
}
7273
}
73-
74-
yield [];
7574
}
7675

7776
/**

0 commit comments

Comments
 (0)