Skip to content

Commit

Permalink
merge master update to current branch
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Nov 30, 2017
1 parent eaa2f15 commit 9ab44a9
Show file tree
Hide file tree
Showing 10 changed files with 284 additions and 58 deletions.
43 changes: 30 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 @@ -26,7 +26,7 @@
## 项目地址

- **github** https://github.com/inhere/php-console.git
- **git@osc** https://git.oschina.net/inhere/php-console.git
- **git@osc** https://gitee.com/inhere/php-console.git

**注意:**

Expand All @@ -39,6 +39,7 @@

```bash
composer require inhere/php-validate
// composer require inhere/php-validate ^1.2
```

- 使用 composer.json
Expand All @@ -56,7 +57,7 @@ composer require inhere/php-validate

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

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

use Inhere\Validate\Validation;

class PageRequest extends Validation
Expand All @@ -88,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 @@ -114,7 +114,7 @@ class PageRequest extends Validation
];
}

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

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

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

Expand Down Expand Up @@ -565,8 +565,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 @@ -596,6 +598,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 @@ -630,7 +633,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 @@ -664,6 +667,7 @@ $v = Validation::make($_POST, [
- 关于布尔值验证
* 如果是 "1"、"true"、"on" 和 "yes",则返回 TRUE
* 如果是 "0"、"false"、"off"、"no" 和 "",则返回 FALSE
- `size/range` `length` 可以只定义 min 最小值。 但是 **当定义了max 值时,必须同时定义最小值**
- 支持对数组的子级值验证

```php
Expand All @@ -681,9 +685,8 @@ $v = Validation::make($_POST, [
['goods.pear', 'max', 30], //goods 下的 pear 值最大不能超过 30
```

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

## 代码示例

Expand All @@ -692,9 +695,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
32 changes: 31 additions & 1 deletion src/Filter/FilterList.php
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,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 Expand Up @@ -307,4 +337,4 @@ public static function callback($val, $callback)
{
return filter_var($val, FILTER_CALLBACK, ['options' => $callback]);
}
}
}
10 changes: 7 additions & 3 deletions src/Utils/ErrorMessageTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ trait ErrorMessageTrait
'notIn' => '{attr} cannot in ({value0})',
'string' => ['{attr} must be a string',
'{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 @@ -50,7 +51,10 @@ trait ErrorMessageTrait
'compare' => '{attr} must be equals to {value0}', 'same' => '{attr} must be equals to {value0}', 'equal' => '{attr} must be equals to {value0}',
'notEqual' => '{attr} can not be equals to {value0}',

'isArray' => '{attr} must be an array', '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', 'strList' => '{attr} must be an array and value is all strings', 'json' => '{attr} must be an json string', 'file' => '{attr} must be an uploaded file', 'image' => '{attr} must be an uploaded image file', 'callback' => '{attr} don\'t pass the test and verify!', '_' => '{attr} validation is not through!'];
'isArray' => '{attr} must be an array', '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', 'file' => '{attr} must be an uploaded file', 'image' => '{attr} must be an uploaded image file', 'callback' => '{attr} don\'t pass the test and verify!', '_' => '{attr} validation is not through!'];
/**
* attribute field translate list
* @var array
Expand Down Expand Up @@ -320,7 +324,7 @@ public function getTranslate($attr)
{
$trans = $this->getTranslates();

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

/**
Expand All @@ -335,4 +339,4 @@ public function setAttrTrans(array $attrTrans)

return $this;
}
}
}
21 changes: 16 additions & 5 deletions src/Utils/Helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -192,13 +192,13 @@ 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 @@ -220,6 +220,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 @@ -247,7 +258,7 @@ public static function getValueOfArray(array $array, $key, $default = null)
}

/**
* @param $cb
* @param callable $cb
* @param array $args
* @return mixed
* @throws \InvalidArgumentException
Expand All @@ -271,4 +282,4 @@ public static function call($cb, ...$args)
}
throw new \InvalidArgumentException('The parameter is not a callable');
}
}
}
6 changes: 3 additions & 3 deletions src/ValidationTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,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 Down Expand Up @@ -167,7 +167,7 @@ public function validate(array $onlyChecked = null, $stopOnError = null)
if ($when && $when instanceof \Closure && $when($data, $this) !== true) {
continue;
}
// clear all options
// clear all keywords options
unset($rule['msg'], $rule['default'], $rule['skipOnEmpty'], $rule['isEmpty'], $rule['when'], $rule['filter']);
// 验证设置, 有一些验证器需要参数。 e.g. size()
$args = $rule;
Expand Down Expand Up @@ -547,4 +547,4 @@ public function getSafeFields()
{
return array_keys($this->_safeData);
}
}
}
Loading

0 comments on commit 9ab44a9

Please sign in to comment.