Skip to content

Commit bc5d983

Browse files
committed
some update. add more validators test, add new validator: numList
1 parent 48a2262 commit bc5d983

File tree

8 files changed

+259
-61
lines changed

8 files changed

+259
-61
lines changed

README.md

Lines changed: 38 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
[![License](https://img.shields.io/packagist/l/inhere/php-validate.svg?style=flat-square)](LICENSE)
44
[![Php Version](https://img.shields.io/badge/php-%3E=7.0-brightgreen.svg?maxAge=2592000)](https://packagist.org/packages/inhere/php-validate)
55
[![Latest Stable Version](http://img.shields.io/packagist/v/inhere/php-validate.svg)](https://packagist.org/packages/inhere/php-validate)
6-
[![git branch](https://img.shields.io/badge/branch-php5-yellow.svg)](https://github.com/inhere/php-validate)
6+
[![git branch](https://img.shields.io/badge/branch-master-yellow.svg)](https://github.com/inhere/php-validate)
77

88
一个简洁小巧且功能完善的php验证、过滤库。仅有几个文件,无依赖。
99

@@ -16,7 +16,7 @@
1616
- 方便的获取错误信息,验证后的安全数据获取
1717
- 已经内置了40多个常用的验证器[内置验证器](#built-in-validators)
1818
- 规则设置参考自 yii 的。部分规则参考自 laravel
19-
- `RuleValidation` 规则配置类似于Yii: 每条规则中,允许多个字段,但只能有一个验证器。
19+
- `Validation/RuleValidation` 规则配置类似于Yii: 每条规则中,允许多个字段,但只能有一个验证器。
2020
- e.g `['tagId,userId,name,email,freeTime', 'required', ...]`(下面的示例都是这种)
2121
- `FieldValidation` 规则配置类似于Laravel: 每条规则中,只能有一个字段,但允许多个验证器。
2222
- e.g `['field', 'required|string:5,10|...', ...]`
@@ -25,8 +25,8 @@
2525
2626
## 项目地址
2727

28-
- **git@osc** https://gitee.com/inhere/php-validate.git
2928
- **github** https://github.com/inhere/php-validate.git
29+
- **git@osc** https://gitee.com/inhere/php-validate.git
3030

3131
**注意:**
3232

@@ -35,7 +35,14 @@
3535

3636
## 安装
3737

38-
- 使用 composer
38+
- 使用 composer 命令
39+
40+
```php
41+
composer require inhere/php-validate
42+
// composer require inhere/php-validate ^2.2
43+
```
44+
45+
- 使用 composer.json
3946

4047
编辑 `composer.json`,在 `require` 添加
4148

@@ -49,8 +56,8 @@
4956
- 直接拉取
5057

5158
```
52-
git clone https://git.oschina.net/inhere/php-validate.git // git@osc
5359
git clone https://github.com/inhere/php-validate.git // github
60+
git clone https://gitee.com/inhere/php-validate.git // git@osc
5461
```
5562

5663
## 使用
@@ -63,7 +70,6 @@ git clone https://github.com/inhere/php-validate.git // github
6370
> 此方式是最为完整的使用方式
6471
6572
```php
66-
6773
use Inhere\Validate\Validation;
6874

6975
class PageRequest extends Validation
@@ -82,7 +88,7 @@ class PageRequest extends Validation
8288
['username', 'string', 'on' => 'scene2' ],
8389
['username', 'regexp' ,'/^[a-z]\w{2,12}$/'],
8490
['title', 'customValidator', 'msg' => '{attr} error msg!' ], // 指定当前规则的消息
85-
['status', function($status) {
91+
['status', function($status) { // 直接使用闭包验证
8692
if (is_int($status) && $status > 3) {
8793
return true;
8894
}
@@ -108,7 +114,7 @@ class PageRequest extends Validation
108114
];
109115
}
110116

111-
// 自定义验证器的提示消息, 更多请看 {@see ValidationTrait::$messages}
117+
// 自定义验证器的提示消息, 默认消息请看 {@see ErrorMessageTrait::$messages}
112118
public function messages()
113119
{
114120
return [
@@ -169,7 +175,7 @@ class SomeController
169175
}
170176
```
171177

172-
### 方式 1: 创建一个新的class,使用 ValidationTrait
178+
### 方式 3: 创建一个新的class,使用 ValidationTrait
173179

174180
创建一个新的class,并使用 Trait `Inhere\Validate\ValidationTrait`。 此方式是高级自定义的使用方式, 可以方便的嵌入到其他类中
175181

@@ -244,7 +250,6 @@ class UserController
244250
}
245251
```
246252

247-
248253
## 添加自定义验证器
249254

250255
- 在继承了 `Inhere\Validate\Validation` 的子类添加验证方法. 请看上面的 **使用方式1**
@@ -559,8 +564,10 @@ public function get(string $key, $default = null)
559564
`float` | 过滤非法字符,保留`float`格式的数据 | `['price', 'float', 'filter' => 'float'],`
560565
`string` | 过滤非法字符并转换为`string`类型 | `['userId', 'number', 'filter' => 'string'],`
561566
`trim` | 去除首尾空白字符,支持数组。 | `['username', 'min', 4, 'filter' => 'trim'],`
562-
`lowercase` | 字符串转换为小写 | `['description', 'min', 4, 'filter' => 'lowercase'],`
563-
`uppercase` | 字符串转换为大写 | `['title', 'min', 4, 'filter' => 'uppercase'],`
567+
`lowercase` | 字符串转换为小写 | `['description', 'string', 'filter' => 'lowercase'],`
568+
`uppercase` | 字符串转换为大写 | `['title', 'string', 'filter' => 'uppercase'],`
569+
`snakeCase` | 字符串转换为蛇形风格 | `['title', 'string', 'filter' => 'snakeCase'],`
570+
`camelCase` | 字符串转换为驼峰风格 | `['title', 'string', 'filter' => 'camelCase'],`
564571
`timestamp/strToTime` | 字符串日期转换时间戳 | `['pulishedAt', 'number', 'filter' => 'strToTime'],`
565572
`abs` | 返回绝对值 | `['field', 'int', 'filter' => 'abs'],`
566573
`url` | URL 过滤,移除所有不符合 URL 的字符 | `['field', 'url', 'filter' => 'url'],`
@@ -590,6 +597,7 @@ public function get(string $key, $default = null)
590597
`isList` | 验证值是否是一个自然数组 list (key是从0自然增长的) | `['tags', 'isList']`
591598
`isArray` | 验证是否是数组 | `['goods', 'isArray']`
592599
`intList` | 验证字段值是否是一个 int list | `['tagIds', 'intList']`
600+
`numList` | 验证字段值是否是一个 number list | `['tagIds', 'numList']`
593601
`strList` | 验证字段值是否是一个 string list | `['tags', 'strList']`
594602
`min` | 最小边界值验证 | `['title', 'min', 40]`
595603
`max` | 最大边界值验证 | `['title', 'max', 40]`
@@ -624,7 +632,7 @@ public function get(string $key, $default = null)
624632
`md5` | 验证是否是 md5 格式的字符串 | `['passwd', 'md5']`
625633
`sha1` | 验证是否是 sha1 格式的字符串 | `['passwd', 'sha1']`
626634
`color` | 验证是否是html color | `['backgroundColor', 'color']`
627-
`regexp` | 使用正则进行验证 | `['name', 'regexp', '/^\w+$/']`
635+
`regex/regexp` | 使用正则进行验证 | `['name', 'regexp', '/^\w+$/']`
628636
`safe` | 用于标记字段是安全的,无需验证 | `['createdAt, updatedAt', 'safe']`
629637

630638
### `safe` 验证器,标记属性/字段是安全的
@@ -658,6 +666,7 @@ $v = Validation::make($_POST, [
658666
- 关于布尔值验证
659667
* 如果是 "1"、"true"、"on" 和 "yes",则返回 TRUE
660668
* 如果是 "0"、"false"、"off"、"no" 和 "",则返回 FALSE
669+
- `size/range` `length` 可以只定义 `min` 最小值。 但是 **当定义了 `max` 值时,必须同时定义最小值**
661670
- 支持对数组的子级值验证
662671

663672
```php
@@ -676,9 +685,7 @@ $v = Validation::make($_POST, [
676685
```
677686

678687
- `required*` 系列规则参考自 laravel
679-
- 验证大小范围 `int` 是比较大小。 `string``array` 是检查长度
680-
- `size/range` `length` 可以只定义 `min` 最小值。 但是 **当定义了 `max` 值时,必须同时定义最小值**
681-
- 验证大小范围 是包含边界值的
688+
- 验证大小范围 `int` 是比较大小。 `string``array` 是检查长度。大小范围 是包含边界值的
682689

683690
## 代码示例
684691

@@ -687,9 +694,23 @@ $v = Validation::make($_POST, [
687694
## 单元测试
688695

689696
```sh
690-
./tests/test.sh
697+
phpunit
691698
```
692699

693700
## License
694701

695702
MIT
703+
704+
## 我的其他项目
705+
706+
### `inhere/console` [github](https://github.com/inhere/php-console) [git@osc](https://git.oschina.net/inhere/php-console)
707+
708+
轻量且功能丰富的命令行应用,工具库, 控制台交互.
709+
710+
### `inhere/sroute` [github](https://github.com/inhere/php-srouter) [git@osc](https://git.oschina.net/inhere/php-srouter)
711+
712+
轻量且快速的路由库
713+
714+
### `inhere/http` [github](https://github.com/inhere/php-http) [git@osc](https://git.oschina.net/inhere/php-http)
715+
716+
http message 工具库(PSR 7 实现)

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "inhere/php-validate",
33
"type": "library",
4-
"description": "a simple validate library of the php",
4+
"description": "a simple validate, filter library of the php",
55
"keywords": ["library", "validate"],
66
"homepage": "http://github.com/inhere/php-validate",
77
"license": "MIT",

src/Filter/FilterList.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,36 @@ public static function uppercase($var)
138138
return Helper::strToUpper($var);
139139
}
140140

141+
/**
142+
* string to snakeCase
143+
* @param string $var
144+
* @param string $sep
145+
* @return string
146+
*/
147+
public static function snakeCase($var, $sep = '_')
148+
{
149+
if (!$var || !\is_string($var)) {
150+
return '';
151+
}
152+
153+
return Helper::toSnakeCase($var, $sep);
154+
}
155+
156+
/**
157+
* string to camelcase
158+
* @param string $var
159+
* @param bool $ucFirst
160+
* @return string
161+
*/
162+
public static function camelCase($var, $ucFirst = false)
163+
{
164+
if (!$var || !\is_string($var)) {
165+
return '';
166+
}
167+
168+
return Helper::toCamelCase($var, $ucFirst);
169+
}
170+
141171
/**
142172
* string to time
143173
* @param string $var

src/Utils/ErrorMessageTrait.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ trait ErrorMessageTrait
6565
'{attr} must be a string and minimum length be {min}',
6666
'{attr} must be a string and length range must be {min} ~ {max}',
6767
],
68+
'regex' => '{attr} does not match the {value0} conditions',
6869
'regexp' => '{attr} does not match the {value0} conditions',
6970

7071
'mustBe' => '{attr} must be equals to {value0}',
@@ -79,6 +80,7 @@ trait ErrorMessageTrait
7980
'isMap' => '{attr} must be an array and is key-value format',
8081
'isList' => '{attr} must be an array of nature',
8182
'intList' => '{attr} must be an array and value is all integers',
83+
'numList' => '{attr} must be an array and value is all numbers',
8284
'strList' => '{attr} must be an array and value is all strings',
8385

8486
'json' => '{attr} must be an json string',
@@ -376,7 +378,7 @@ public function getTranslate(string $attr): string
376378
{
377379
$trans = $this->getTranslates();
378380

379-
return $trans[$attr] ?? Helper::toSnakeCase($attr, ' ');
381+
return $trans[$attr] ?? Helper::beautifyFieldName($attr);
380382
}
381383

382384
/**

src/Utils/Helper.php

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -214,14 +214,14 @@ public static function ucwords($str)
214214
* Translates a string with underscores into camel case (e.g. first_name -> firstName)
215215
* @prototype string public static function toCamelCase(string $str[, bool $capitalise_first_char = false])
216216
* @param $str
217-
* @param bool $upper_case_first_char
217+
* @param bool $upperCaseFirstChar
218218
* @return mixed
219219
*/
220-
public static function toCamelCase($str, $upper_case_first_char = false)
220+
public static function toCamelCase($str, $upperCaseFirstChar = false)
221221
{
222222
$str = self::strToLower($str);
223223

224-
if ($upper_case_first_char) {
224+
if ($upperCaseFirstChar) {
225225
$str = self::ucfirst($str);
226226
}
227227

@@ -243,6 +243,17 @@ public static function toSnakeCase($string, $sep = '_')
243243
return self::strToLower(trim(preg_replace('/([A-Z][a-z])/', $sep . '$1', $string), $sep));
244244
}
245245

246+
/**
247+
* @param string $field
248+
* @return mixed|string
249+
*/
250+
public static function beautifyFieldName($field)
251+
{
252+
$str = self::toSnakeCase($field, ' ');
253+
254+
return strpos($str, '_') ? str_replace('_', ' ', $str) : $str;
255+
}
256+
246257
/**
247258
* getValueOfArray 支持以 '.' 分割进行子级值获取 eg: 'goods.apple'
248259
* @param array $array
@@ -272,7 +283,7 @@ public static function getValueOfArray(array $array, $key, $default = null)
272283
}
273284

274285
/**
275-
* @param $cb
286+
* @param callable $cb
276287
* @param array $args
277288
* @return mixed
278289
* @throws \InvalidArgumentException

src/ValidationTrait.php

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
/**
1717
* Trait ValidationTrait
1818
* @package Inhere\Validate
19-
* @property array $data To verify the data list. please define it on main class. 待验证的数据列表
19+
* property array $data To verify the data list. please define it on main class. 待验证的数据列表
2020
*/
2121
trait ValidationTrait
2222
{
@@ -34,11 +34,8 @@ trait ValidationTrait
3434
*/
3535
protected $scene = '';
3636

37-
/**
38-
* Through the validation of the data
39-
* @var array
40-
*/
41-
private $_safeData = [];
37+
/** @var array used rules at current scene */
38+
protected $_usedRules = [];
4239

4340
/**
4441
* the rules is by setRules()
@@ -47,10 +44,10 @@ trait ValidationTrait
4744
private $_rules = [];
4845

4946
/**
50-
* used rules at current scene
47+
* Through the validation of the data
5148
* @var array
5249
*/
53-
protected $_usedRules = [];
50+
private $_safeData = [];
5451

5552
/** @var bool */
5653
private $_validated = false;
@@ -185,7 +182,7 @@ public function validate(array $onlyChecked = null, $stopOnError = null)
185182
continue;
186183
}
187184

188-
// clear all options
185+
// clear all keywords options
189186
unset($rule['msg'], $rule['default'], $rule['skipOnEmpty'], $rule['isEmpty'], $rule['when'], $rule['filter']);
190187

191188
// 验证设置, 有一些验证器需要参数。 e.g. size()

0 commit comments

Comments
 (0)