Skip to content

Commit

Permalink
some update. add more validators test, add new validator: numList
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Nov 30, 2017
1 parent 48a2262 commit bc5d983
Show file tree
Hide file tree
Showing 8 changed files with 259 additions and 61 deletions.
55 changes: 38 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
[![License](https://img.shields.io/packagist/l/inhere/php-validate.svg?style=flat-square)](LICENSE)
[![Php Version](https://img.shields.io/badge/php-%3E=7.0-brightgreen.svg?maxAge=2592000)](https://packagist.org/packages/inhere/php-validate)
[![Latest Stable Version](http://img.shields.io/packagist/v/inhere/php-validate.svg)](https://packagist.org/packages/inhere/php-validate)
[![git branch](https://img.shields.io/badge/branch-php5-yellow.svg)](https://github.com/inhere/php-validate)
[![git branch](https://img.shields.io/badge/branch-master-yellow.svg)](https://github.com/inhere/php-validate)

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

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

- **git@osc** https://gitee.com/inhere/php-validate.git
- **github** https://github.com/inhere/php-validate.git
- **git@osc** https://gitee.com/inhere/php-validate.git

**注意:**

Expand All @@ -35,7 +35,14 @@

## 安装

- 使用 composer
- 使用 composer 命令

```php
composer require inhere/php-validate
// composer require inhere/php-validate ^2.2
```

- 使用 composer.json

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

Expand All @@ -49,8 +56,8 @@
- 直接拉取

```
git clone https://git.oschina.net/inhere/php-validate.git // git@osc
git clone https://github.com/inhere/php-validate.git // github
git clone https://gitee.com/inhere/php-validate.git // git@osc
```

## 使用
Expand All @@ -63,7 +70,6 @@ git clone https://github.com/inhere/php-validate.git // github
> 此方式是最为完整的使用方式
```php

use Inhere\Validate\Validation;

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

// 自定义验证器的提示消息, 更多请看 {@see ValidationTrait::$messages}
// 自定义验证器的提示消息, 默认消息请看 {@see ErrorMessageTrait::$messages}
public function messages()
{
return [
Expand Down Expand Up @@ -169,7 +175,7 @@ class SomeController
}
```

### 方式 1: 创建一个新的class,使用 ValidationTrait
### 方式 3: 创建一个新的class,使用 ValidationTrait

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

Expand Down Expand Up @@ -244,7 +250,6 @@ class UserController
}
```


## 添加自定义验证器

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

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

```php
Expand All @@ -676,9 +685,7 @@ $v = Validation::make($_POST, [
```

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

## 代码示例

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

```sh
./tests/test.sh
phpunit
```

## License

MIT

## 我的其他项目

### `inhere/console` [github](https://github.com/inhere/php-console) [git@osc](https://git.oschina.net/inhere/php-console)

轻量且功能丰富的命令行应用,工具库, 控制台交互.

### `inhere/sroute` [github](https://github.com/inhere/php-srouter) [git@osc](https://git.oschina.net/inhere/php-srouter)

轻量且快速的路由库

### `inhere/http` [github](https://github.com/inhere/php-http) [git@osc](https://git.oschina.net/inhere/php-http)

http message 工具库(PSR 7 实现)
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "inhere/php-validate",
"type": "library",
"description": "a simple validate library of the php",
"description": "a simple validate, filter library of the php",
"keywords": ["library", "validate"],
"homepage": "http://github.com/inhere/php-validate",
"license": "MIT",
Expand Down
30 changes: 30 additions & 0 deletions src/Filter/FilterList.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,36 @@ public static function uppercase($var)
return Helper::strToUpper($var);
}

/**
* string to snakeCase
* @param string $var
* @param string $sep
* @return string
*/
public static function snakeCase($var, $sep = '_')
{
if (!$var || !\is_string($var)) {
return '';
}

return Helper::toSnakeCase($var, $sep);
}

/**
* string to camelcase
* @param string $var
* @param bool $ucFirst
* @return string
*/
public static function camelCase($var, $ucFirst = false)
{
if (!$var || !\is_string($var)) {
return '';
}

return Helper::toCamelCase($var, $ucFirst);
}

/**
* string to time
* @param string $var
Expand Down
4 changes: 3 additions & 1 deletion src/Utils/ErrorMessageTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ trait ErrorMessageTrait
'{attr} must be a string and minimum length be {min}',
'{attr} must be a string and length range must be {min} ~ {max}',
],
'regex' => '{attr} does not match the {value0} conditions',
'regexp' => '{attr} does not match the {value0} conditions',

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

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

return $trans[$attr] ?? Helper::toSnakeCase($attr, ' ');
return $trans[$attr] ?? Helper::beautifyFieldName($attr);
}

/**
Expand Down
19 changes: 15 additions & 4 deletions src/Utils/Helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -214,14 +214,14 @@ public static function ucwords($str)
* Translates a string with underscores into camel case (e.g. first_name -> firstName)
* @prototype string public static function toCamelCase(string $str[, bool $capitalise_first_char = false])
* @param $str
* @param bool $upper_case_first_char
* @param bool $upperCaseFirstChar
* @return mixed
*/
public static function toCamelCase($str, $upper_case_first_char = false)
public static function toCamelCase($str, $upperCaseFirstChar = false)
{
$str = self::strToLower($str);

if ($upper_case_first_char) {
if ($upperCaseFirstChar) {
$str = self::ucfirst($str);
}

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

/**
* @param string $field
* @return mixed|string
*/
public static function beautifyFieldName($field)
{
$str = self::toSnakeCase($field, ' ');

return strpos($str, '_') ? str_replace('_', ' ', $str) : $str;
}

/**
* getValueOfArray 支持以 '.' 分割进行子级值获取 eg: 'goods.apple'
* @param array $array
Expand Down Expand Up @@ -272,7 +283,7 @@ public static function getValueOfArray(array $array, $key, $default = null)
}

/**
* @param $cb
* @param callable $cb
* @param array $args
* @return mixed
* @throws \InvalidArgumentException
Expand Down
15 changes: 6 additions & 9 deletions src/ValidationTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
/**
* Trait ValidationTrait
* @package Inhere\Validate
* @property array $data To verify the data list. please define it on main class. 待验证的数据列表
* property array $data To verify the data list. please define it on main class. 待验证的数据列表
*/
trait ValidationTrait
{
Expand All @@ -34,11 +34,8 @@ trait ValidationTrait
*/
protected $scene = '';

/**
* Through the validation of the data
* @var array
*/
private $_safeData = [];
/** @var array used rules at current scene */
protected $_usedRules = [];

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

/**
* used rules at current scene
* Through the validation of the data
* @var array
*/
protected $_usedRules = [];
private $_safeData = [];

/** @var bool */
private $_validated = false;
Expand Down Expand Up @@ -185,7 +182,7 @@ public function validate(array $onlyChecked = null, $stopOnError = null)
continue;
}

// clear all options
// clear all keywords options
unset($rule['msg'], $rule['default'], $rule['skipOnEmpty'], $rule['isEmpty'], $rule['when'], $rule['filter']);

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

0 comments on commit bc5d983

Please sign in to comment.