diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml index 1eca669..a90bb46 100644 --- a/.github/workflows/php.yml +++ b/.github/workflows/php.yml @@ -17,15 +17,8 @@ jobs: strategy: fail-fast: true matrix: - php: [7.3, 7.4, 8.0, 8.1] # 7.1, 7.2, + php: [ 8.1] # 7.1, 7.2, os: [ubuntu-latest] # windows-latest, macOS-latest - include: - - os: 'ubuntu-latest' - php: '7.2' - phpunit: '8.5.13' - - os: 'ubuntu-latest' - php: '7.1' - phpunit: '7.5.20' steps: - name: Checkout diff --git a/README.en.md b/README.en.md index b3f5d39..7439ee6 100644 --- a/README.en.md +++ b/README.en.md @@ -1,7 +1,7 @@ # PHP Validate [![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.1-brightgreen.svg?maxAge=2592000)](https://packagist.org/packages/inhere/php-validate) +[![Php Version](https://img.shields.io/badge/php-%3E=8.1-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) [![Coverage Status](https://coveralls.io/repos/github/inhere/php-validate/badge.svg?branch=master)](https://coveralls.io/github/inhere/php-validate?branch=master) [![Github Actions Status](https://github.com/inhere/php-validate/workflows/Unit-tests/badge.svg)](https://github.com/inhere/php-validate/actions) diff --git a/README.md b/README.md index 40388b1..dd7de19 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # PHP Validate [![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.1-brightgreen.svg?maxAge=2592000)](https://packagist.org/packages/inhere/php-validate) +[![Php Version](https://img.shields.io/badge/php-%3E=8.1-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) [![Coverage Status](https://coveralls.io/repos/github/inhere/php-validate/badge.svg?branch=master)](https://coveralls.io/github/inhere/php-validate?branch=master) [![Github Actions Status](https://github.com/inhere/php-validate/workflows/Unit-tests/badge.svg)](https://github.com/inhere/php-validate/actions) @@ -59,15 +59,20 @@ validate 同时支持两种规则配置方式,对应了两种规则的收集 - **github** - **gitee** -> **注意:** master 分支是要求 `php7.1+` 的(推荐使用)。`1.x` 分支是支持php5的代码分支,但是基本上不再维护。 - ## 安装 ```bash composer require inhere/php-validate -// composer require inhere/php-validate ^2.2 +# or +# composer require inhere/php-validate ^3.0 ``` +### 注意 + +- `master` 分支是要求 `php8.1+` 的(推荐使用) +- `2.x` 分支是支持 `php7.1+`,但是基本上不再维护。 +- `1.x` 分支是支持php5的代码分支,但是基本上不再维护。 + ## 立即使用 diff --git a/composer.json b/composer.json index 1e588f5..82a19b2 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,7 @@ { "name": "inhere/php-validate", "type": "library", - "description": "an simple validate, filter library of the php", + "description": "generic data validate, filter library of the php", "keywords": [ "php-library", "library", @@ -19,11 +19,11 @@ } ], "require": { - "php": ">7.1.0", - "toolkit/stdlib": "~1.0" + "php": ">8.1.0", + "toolkit/stdlib": "~2.0" }, "require-dev": { - "phpunit/phpunit": "^7.5 || ^8.5 || ^9.5" + "phpunit/phpunit": "^9.5" }, "autoload": { "psr-4": { diff --git a/src/Exception/ValidateException.php b/src/Exception/ValidateException.php index acc262e..c82c902 100644 --- a/src/Exception/ValidateException.php +++ b/src/Exception/ValidateException.php @@ -14,7 +14,7 @@ class ValidateException extends RuntimeException /** * @var string */ - public $field; + public string $field; /** * @param string $field diff --git a/src/Filter/FilteringTrait.php b/src/Filter/FilteringTrait.php index bf339ec..e3293f4 100644 --- a/src/Filter/FilteringTrait.php +++ b/src/Filter/FilteringTrait.php @@ -25,36 +25,36 @@ trait FilteringTrait { /** @var array user custom filters */ - private $_filters = []; + private array $_filters = []; /** * value sanitize 直接对给的值进行过滤 * - * @param mixed $value - * @param string|array $filters - * string: + * filters: + * string: * 'string|trim|upper' - * array: - * [ + * array: + * [ * 'string', * 'trim', * ['Class', 'method'], * // 追加额外参数. 传入时,第一个参数总是要过滤的字段值,其余的依次追加 * 'myFilter' => ['arg1', 'arg2'], * function($val) { - * return str_replace(' ', '', $val); + * return str_replace(' ', '', $val); * }, - * ] + * ] + * + * @param mixed $value + * @param array|string|callable $filters * * @return mixed - * @throws InvalidArgumentException */ - protected function valueFiltering($value, $filters) + protected function valueFiltering(mixed $value, array|string|callable $filters): mixed { - $filters = is_string($filters) ? Filters::explode($filters, '|') : $filters; - - // fix: must ensure is array - if (!is_array($filters)) { + if (is_string($filters)) { + $filters = Filters::explode($filters, '|'); + } elseif (!is_array($filters)) { $filters = [$filters]; } @@ -64,14 +64,14 @@ protected function valueFiltering($value, $filters) $args = (array)$filter; $value = $this->callStringCallback($key, $value, ...$args); - // closure + // closure } elseif (is_object($filter) && method_exists($filter, '__invoke')) { $value = $filter($value); - // string, trim, .... + // string, trim, .... } elseif (is_string($filter)) { $value = $this->callStringCallback($filter, $value); - // e.g ['Class', 'method'], + // e.g ['Class', 'method'], } else { $value = Helper::call($filter, $value); } @@ -87,7 +87,7 @@ protected function valueFiltering($value, $filters) * @return mixed * @throws InvalidArgumentException */ - protected function callStringCallback(string $filter, ...$args) + protected function callStringCallback(string $filter, ...$args): mixed { // if is alias name $filterName = Filters::realName($filter); @@ -95,21 +95,21 @@ protected function callStringCallback(string $filter, ...$args) // if $filter is a custom by addFiler() if ($callback = $this->getFilter($filter)) { $value = $callback(...$args); - // if $filter is a custom method of the subclass. + // if $filter is a custom method of the subclass. } elseif (method_exists($this, $filter . 'Filter')) { $filter .= 'Filter'; $value = $this->$filter(...$args); - // if $filter is a custom add callback in the property {@see $_filters}. + // if $filter is a custom add callback in the property {@see $_filters}. } elseif ($callback = UserFilters::get($filter)) { $value = $callback(...$args); - // if $filter is a custom add callback in the property {@see $_filters}. + // if $filter is a custom add callback in the property {@see $_filters}. // $filter is a method of the class 'FilterList' } elseif (method_exists(Filters::class, $filterName)) { $value = Filters::$filterName(...$args); - // it is function name + // it is function name } elseif (function_exists($filter)) { $value = $filter(...$args); } else { @@ -134,28 +134,27 @@ public function getFilter(string $name): ?callable } /** - * @param string $name + * @param string $name * @param callable $filter * - * @return $this + * @return static */ - public function addFilter(string $name, callable $filter): self + public function addFilter(string $name, callable $filter): static { return $this->setFilter($name, $filter); } /** - * @param string $name + * @param string $name * @param callable $filter * - * @return $this + * @return static */ - public function setFilter(string $name, callable $filter): self + public function setFilter(string $name, callable $filter): static { if ($name = trim($name)) { $this->_filters[$name] = $filter; } - return $this; } diff --git a/src/Filter/Filters.php b/src/Filter/Filters.php index 475ae7b..1221fd2 100644 --- a/src/Filter/Filters.php +++ b/src/Filter/Filters.php @@ -40,7 +40,6 @@ use const FILTER_SANITIZE_EMAIL; use const FILTER_SANITIZE_ENCODED; use const FILTER_SANITIZE_FULL_SPECIAL_CHARS; -use const FILTER_SANITIZE_MAGIC_QUOTES; use const FILTER_SANITIZE_NUMBER_FLOAT; use const FILTER_SANITIZE_NUMBER_INT; use const FILTER_SANITIZE_SPECIAL_CHARS; @@ -48,7 +47,6 @@ use const FILTER_UNSAFE_RAW; use const FILTER_VALIDATE_BOOLEAN; use const MB_CASE_TITLE; -use const PHP_VERSION_ID; /** * Class Filters @@ -60,7 +58,7 @@ final class Filters use NameAliasTrait; /** @var array filter aliases map */ - private static $aliases = [ + private static array $aliases = [ 'substr' => 'subStr', 'substring' => 'subStr', 'str2list' => 'explode', @@ -85,11 +83,11 @@ final class Filters * 注意: NULL 不是标量类型 * * @param mixed $val - * @param bool $nullAsFalse + * @param bool $nullAsFalse * * @return bool */ - public static function boolean($val, $nullAsFalse = false): bool + public static function boolean(mixed $val, bool $nullAsFalse = false): bool { if ($val !== null && !is_scalar($val)) { return (bool)$val; @@ -102,9 +100,8 @@ public static function boolean($val, $nullAsFalse = false): bool /** * @see Validators::boolean() - * {@inheritdoc} */ - public static function bool($val, $nullAsFalse = false): bool + public static function bool(mixed $val, $nullAsFalse = false): bool { return self::boolean($val, $nullAsFalse); } @@ -118,7 +115,7 @@ public static function bool($val, $nullAsFalse = false): bool * * @return int|array */ - public static function integer($val) + public static function integer(mixed $val): array|int { if (is_array($val)) { return array_map(self::class . '::integer', $val); @@ -129,9 +126,8 @@ public static function integer($val) /** * @see Filters::integer() - * {@inheritdoc} */ - public static function int($val) + public static function int(mixed $val): array|int { return self::integer($val); } @@ -141,7 +137,7 @@ public static function int($val) * * @return int */ - public static function abs($val): int + public static function abs(mixed $val): int { return abs((int)$val); } @@ -152,15 +148,15 @@ public static function abs($val): int * @note 该过滤器默认允许所有数字以及 + - * * @param mixed $val 要过滤的变量 - * @param null|int $decimal - * @param int $flags 标志 + * @param int|null $decimal + * @param int|string $flags 标志 * FILTER_FLAG_ALLOW_FRACTION - 允许小数分隔符 (比如 .) * FILTER_FLAG_ALLOW_THOUSAND - 允许千位分隔符(比如 ,) * FILTER_FLAG_ALLOW_SCIENTIFIC - 允许科学记数法(比如 e 和 E) * - * @return mixed + * @return int|float */ - public static function float($val, $decimal = null, $flags = FILTER_FLAG_ALLOW_FRACTION) + public static function float(mixed $val, int $decimal = null, int|string $flags = FILTER_FLAG_ALLOW_FRACTION): int|float { $options = (int)$flags !== 0 ? ['flags' => (int)$flags] : []; @@ -177,8 +173,8 @@ public static function float($val, $decimal = null, $flags = FILTER_FLAG_ALLOW_F /** * 去除标签,去除或编码特殊字符。 * - * @param string|array $val - * @param int $flags 标志 + * @param mixed $val + * @param int|string $flags 标志 * FILTER_FLAG_NO_ENCODE_QUOTES - 该标志不编码引号 * FILTER_FLAG_STRIP_LOW - 去除 ASCII 值在 32 以下的字符 * FILTER_FLAG_STRIP_HIGH - 去除 ASCII 值在 127 以上的字符 @@ -188,7 +184,7 @@ public static function float($val, $decimal = null, $flags = FILTER_FLAG_ALLOW_F * * @return string|array */ - public static function string($val, $flags = 0) + public static function string(mixed $val, int|string $flags = 0): array|string { if (is_array($val)) { return array_map(self::class . '::string', $val); @@ -196,14 +192,13 @@ public static function string($val, $flags = 0) $options = (int)$flags !== 0 ? ['flags' => (int)$flags] : []; - return (string)filter_var($val, FILTER_SANITIZE_FULL_SPECIAL_CHARS, $options); + return (string)filter_var((string)$val, FILTER_SANITIZE_FULL_SPECIAL_CHARS, $options); } /** * @see Filters::string() - * {@inheritdoc} */ - public static function stripped($val, $flags = 0) + public static function stripped($val, int|string $flags = 0): array|string { return self::string($val, $flags); } @@ -215,23 +210,23 @@ public static function stripped($val, $flags = 0) * * @return string New string */ - public static function nl2br($str): string + public static function nl2br(string $str): string { - return str_replace(["\r\n", "\r", "\n"], '
', (string)$str); + return str_replace(["\r\n", "\r", "\n"], '
', $str); } /** * simple trim space * - * @param string|array $val + * @param array|string $val * * @return string|array */ - public static function trim($val) + public static function trim(array|string $val): array|string { - return is_array($val) ? array_map(function ($val) { + return is_array($val) ? array_map(static function ($val) { return is_string($val) ? trim($val) : $val; - }, $val) : trim((string)$val); + }, $val) : trim($val); } /** @@ -241,9 +236,9 @@ public static function trim($val) * * @return mixed */ - public static function clearSpace($val): string + public static function clearSpace(string $val): string { - return str_replace(' ', '', trim((string)$val)); + return str_replace(' ', '', trim($val)); } /** @@ -253,9 +248,9 @@ public static function clearSpace($val): string * * @return mixed */ - public static function clearNewline($val): string + public static function clearNewline(string $val): string { - return str_replace(["\r\n", "\r", "\n"], '', trim((string)$val)); + return str_replace(["\r\n", "\r", "\n"], '', trim($val)); } /** @@ -265,7 +260,7 @@ public static function clearNewline($val): string * * @return string */ - public static function lower($val): string + public static function lower(string $val): string { return self::lowercase($val); } @@ -273,11 +268,11 @@ public static function lower($val): string /** * string to lowercase * - * @param string|int $val + * @param int|string $val * * @return string */ - public static function lowercase($val): string + public static function lowercase(int|string $val): string { if (!$val || !is_string($val)) { return is_int($val) ? (string)$val : ''; @@ -297,7 +292,7 @@ public static function lowercase($val): string * * @return string */ - public static function upper($val): string + public static function upper(string $val): string { return self::uppercase($val); } @@ -305,11 +300,11 @@ public static function upper($val): string /** * string to uppercase * - * @param string|int $str + * @param int|string $str * * @return string */ - public static function uppercase($str): string + public static function uppercase(int|string $str): string { if (!$str || !is_string($str)) { return is_int($str) ? (string)$str : ''; @@ -323,13 +318,13 @@ public static function uppercase($str): string } /** - * @param string|mixed $str + * @param string $str * * @return string */ - public static function ucfirst($str): string + public static function ucfirst(string $str): string { - if (!$str || !is_string($str)) { + if (!$str) { return ''; } @@ -337,13 +332,13 @@ public static function ucfirst($str): string } /** - * @param string|mixed $str + * @param string $str * * @return string */ - public static function ucwords($str): string + public static function ucwords(string $str): string { - if (!$str || !is_string($str)) { + if (!$str) { return ''; } @@ -362,7 +357,7 @@ public static function ucwords($str): string * * @return string */ - public static function snake($val, string $sep = '_'): string + public static function snake(string $val, string $sep = '_'): string { return self::snakeCase($val, $sep); } @@ -377,9 +372,9 @@ public static function snake($val, string $sep = '_'): string * * @return string */ - public static function snakeCase($val, string $sep = '_'): string + public static function snakeCase(string $val, string $sep = '_'): string { - if (!$val || !is_string($val)) { + if (!$val) { return ''; } @@ -391,12 +386,12 @@ public static function snakeCase($val, string $sep = '_'): string /** * string to camelcase * - * @param string|mixed $val - * @param bool $ucFirst + * @param string $val + * @param bool $ucFirst * * @return string */ - public static function camel($val, $ucFirst = false): string + public static function camel(string $val, bool $ucFirst = false): string { return self::camelCase($val, $ucFirst); } @@ -405,23 +400,22 @@ public static function camel($val, $ucFirst = false): string * Translates a string with underscores into camel case (e.g. first_name -> firstName) * * @param string $val - * @param bool $ucFirst + * @param bool $ucFirst * * @return string */ - public static function camelCase($val, $ucFirst = false): string + public static function camelCase(string $val, bool $ucFirst = false): string { - if (!$val || !is_string($val)) { + if (!$val) { return ''; } $str = self::lowercase($val); - if ($ucFirst) { $str = self::ucfirst($str); } - return preg_replace_callback('/_+([a-z])/', function ($c) { + return preg_replace_callback('/_+([a-z])/', static function ($c) { return strtoupper($c[1]); }, $str); } @@ -433,7 +427,7 @@ public static function camelCase($val, $ucFirst = false): string * * @return int */ - public static function timestamp($val): int + public static function timestamp(string $val): int { return self::strToTime($val); } @@ -445,9 +439,9 @@ public static function timestamp($val): int * * @return int */ - public static function strToTime($val): int + public static function strToTime(string $val): int { - if (!$val || !is_string($val)) { + if (!$val) { return 0; } @@ -462,7 +456,7 @@ public static function strToTime($val): int * * @return bool|string */ - public static function subStr(string $str, int $start, int $length = 0, string $encoding = 'utf-8') + public static function subStr(string $str, int $start, int $length = 0, string $encoding = 'utf-8'): bool|string { $length = $length === 0 ? Helper::strlen($str) : $length; @@ -511,22 +505,22 @@ public static function str2array(string $string, string $delimiter = ',', int $l /** * @param mixed $val - * @param null|string $allowedTags + * @param string|null $allowedTags * * @return string */ - public static function clearTags($val, $allowedTags = null): string + public static function clearTags(mixed $val, string $allowedTags = null): string { return self::stripTags($val, $allowedTags); } /** * @param mixed $val - * @param null|string $allowedTags e.g '

' 允许

+ * @param string|null $allowedTags e.g '

' 允许

* * @return string */ - public static function stripTags($val, $allowedTags = null): string + public static function stripTags(mixed $val, string $allowedTags = null): string { if (!$val || !is_string($val)) { return ''; @@ -565,12 +559,7 @@ public static function encoded(string $val, int $flags = 0): string */ public static function quotes(string $val): string { - if (PHP_VERSION_ID > 70300) { - /** @noinspection PhpElementIsNotAvailableInCurrentPhpVersionInspection */ - $flag = FILTER_SANITIZE_ADD_SLASHES; - } else { - $flag = FILTER_SANITIZE_MAGIC_QUOTES; - } + $flag = FILTER_SANITIZE_ADD_SLASHES; return (string)filter_var($val, $flag); } @@ -586,7 +575,7 @@ public static function quotes(string $val): string * * @return string */ - public static function specialChars($val, int $flags = 0): string + public static function specialChars(string $val, int $flags = 0): string { $settings = $flags !== 0 ? ['flags' => $flags] : []; @@ -595,11 +584,11 @@ public static function specialChars($val, int $flags = 0): string /** * @param string $val - * @param int $flags + * @param int $flags * * @return string */ - public static function escape($val, $flags = 0): string + public static function escape(string $val, int $flags = 0): string { return self::specialChars($val, $flags); } @@ -612,7 +601,7 @@ public static function escape($val, $flags = 0): string * * @return string */ - public static function fullSpecialChars($val, int $flags = 0): string + public static function fullSpecialChars(string $val, int $flags = 0): string { $settings = $flags !== 0 ? ['flags' => $flags] : []; @@ -622,29 +611,25 @@ public static function fullSpecialChars($val, int $flags = 0): string /** * 字符串长度过滤截取 * - * @param string $string - * @param integer $start - * @param int $length + * @param string $string + * @param int|string $start + * @param int|string $length * * @return string */ - public static function stringCute($string, $start = 0, $length = 0): string + public static function stringCute(string $string, int|string $start = 0, int|string $length = 0): string { - if (!is_string($string)) { - return ''; - } - return self::subStr($string, (int)$start, (int)$length); } /** * @param string $string - * @param int $start - * @param int $length + * @param int|string $start + * @param int|string $length * * @return string */ - public static function cut($string, $start = 0, $length = 0): string + public static function cut(string $string, int|string $start = 0, int|string $length = 0): string { return self::stringCute($string, $start, $length); } @@ -652,18 +637,14 @@ public static function cut($string, $start = 0, $length = 0): string /** * url地址过滤 移除所有不符合 url 的字符 * - * @note 该过滤器允许所有的字母、数字以及 $-_.+!*'(),{}|\^~[]`"><#%;/?:@&= + * - 该过滤器允许所有的字母、数字以及 $-_.+!*'(),{}|\^~[]`"><#%;/?:@&= * * @param string $val 要过滤的数据 * * @return string */ - public static function url($val): string + public static function url(string $val): string { - if (!is_string($val)) { - return ''; - } - return (string)filter_var($val, FILTER_SANITIZE_URL); } @@ -674,12 +655,8 @@ public static function url($val): string * * @return string */ - public static function email($val): string + public static function email(string $val): string { - if (!is_string($val)) { - return ''; - } - return (string)filter_var($val, FILTER_SANITIZE_EMAIL); } @@ -689,7 +666,7 @@ public static function email($val): string * 如果不规定标志,则该过滤器没有任何行为。 * * @param string $string - * @param int $flags 标志 + * @param int|string $flags 标志 * FILTER_FLAG_STRIP_LOW - 去除 ASCII 值在 32 以下的字符 * FILTER_FLAG_STRIP_HIGH - 去除 ASCII 值在 32 以上的字符 * FILTER_FLAG_ENCODE_LOW - 编码 ASCII 值在 32 以下的字符 @@ -698,7 +675,7 @@ public static function email($val): string * * @return string|mixed */ - public static function unsafeRaw($string, $flags = 0) + public static function unsafeRaw(string $string, int|string $flags = 0): mixed { $settings = (int)$flags !== 0 ? ['flags' => (int)$flags] : []; @@ -713,7 +690,7 @@ public static function unsafeRaw($string, $flags = 0) * * @return bool|mixed */ - public static function callback($val, $callback) + public static function callback(mixed $val, callable $callback): mixed { return filter_var($val, FILTER_CALLBACK, ['options' => $callback]); } @@ -725,7 +702,7 @@ public static function callback($val, $callback) * * @return array */ - public static function unique($val): array + public static function unique(mixed $val): array { if (!$val || !is_array($val)) { return (array)$val; diff --git a/src/Filter/Filtration.php b/src/Filter/Filtration.php index 3db8ca9..7163889 100644 --- a/src/Filter/Filtration.php +++ b/src/Filter/Filtration.php @@ -8,7 +8,6 @@ namespace Inhere\Validate\Filter; -use InvalidArgumentException; use function array_merge; use function is_string; @@ -29,10 +28,10 @@ class Filtration use FilteringTrait; /** @var array raw data */ - private $_data; + private array $_data; /** @var array the rules is by setRules() */ - private $_rules; + private array $_rules; /** * @param array $data @@ -72,7 +71,6 @@ public function load(array $data): self * @param array $rules * * @return array - * @throws InvalidArgumentException */ public function filtering(array $rules = []): array { @@ -86,7 +84,6 @@ public function filtering(array $rules = []): array * @param array $data * * @return array Return filtered data - * @throws InvalidArgumentException */ public function applyRules(array $rules = [], array $data = []): array { @@ -122,12 +119,11 @@ public function applyRules(array $rules = [], array $data = []): array * value sanitize Filter the value directly * * @param mixed $value - * @param string|array $filters + * @param array|string $filters * * @return mixed - * @throws InvalidArgumentException */ - public function sanitize($value, $filters) + public function sanitize(mixed $value, array|string $filters): mixed { return $this->valueFiltering($value, $filters); } @@ -135,14 +131,13 @@ public function sanitize($value, $filters) /** * get a field value from {@see $data} * - * @param string|int $field - * @param string|array $filters - * @param mixed $default + * @param int|string $field + * @param array|string|null $filters + * @param mixed|null $default * * @return mixed - * @throws InvalidArgumentException */ - public function get($field, $filters = null, $default = null) + public function get(int|string $field, array|string $filters = null, mixed $default = null): mixed { if (!isset($this->_data[$field])) { return $default; @@ -158,11 +153,11 @@ public function get($field, $filters = null, $default = null) } /** - * @param string|int $field + * @param int|string $field * * @return bool */ - public function has($field): bool + public function has(int|string $field): bool { return isset($this->_data[$field]); } diff --git a/src/Filter/UserFilters.php b/src/Filter/UserFilters.php index 21d452e..fac166f 100644 --- a/src/Filter/UserFilters.php +++ b/src/Filter/UserFilters.php @@ -18,7 +18,7 @@ final class UserFilters /** * @var array user custom filters */ - private static $filters = []; + private static array $filters = []; /** * @param string $name diff --git a/src/GlobalOption.php b/src/GlobalOption.php index 0b90dfa..b0b320c 100644 --- a/src/GlobalOption.php +++ b/src/GlobalOption.php @@ -14,5 +14,5 @@ final class GlobalOption * * @var bool */ - public static $prettifyName = true; + public static bool $prettifyName = true; } diff --git a/src/Helper.php b/src/Helper.php index 4dcf57b..dae18a6 100644 --- a/src/Helper.php +++ b/src/Helper.php @@ -55,7 +55,7 @@ class Helper * * @link https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types */ - public static $imgMimeTypes = [ + public static array $imgMimeTypes = [ 'bmp' => 'image/bmp', 'gif' => 'image/gif', 'ief' => 'image/ief', @@ -70,7 +70,7 @@ class Helper /** * @var array */ - public static $imgMimeConstants = [ + public static array $imgMimeConstants = [ IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, @@ -80,7 +80,7 @@ class Helper ]; /** @var string */ - public static $fileValidators = '|file|image|mimeTypes|mimes|'; + public static string $fileValidators = '|file|image|mimeTypes|mimes|'; /** * @param string $ext @@ -128,11 +128,11 @@ public static function getMimeType(string $file): string } /** - * @param int|string|array $val + * @param array|int|string $val * * @return int */ - public static function length($val): int + public static function length(array|int|string $val): int { if (is_int($val)) { return $val; @@ -170,7 +170,7 @@ public static function strlen(string $str, string $encoding = 'UTF-8'): int * * @return bool|int */ - public static function strPos(string $str, $find, int $offset = 0, $encoding = 'UTF-8') + public static function strPos(string $str, string $find, int $offset = 0, string $encoding = 'UTF-8'): bool|int { if (function_exists('mb_strpos')) { return mb_strpos($str, $find, $offset, $encoding); @@ -187,7 +187,7 @@ public static function strPos(string $str, $find, int $offset = 0, $encoding = ' * * @return bool|int */ - public static function strrpos(string $str, $find, int $offset = 0, string $encoding = 'utf-8') + public static function strrpos(string $str, string $find, int $offset = 0, string $encoding = 'utf-8'): bool|int { if (function_exists('mb_strrpos')) { return mb_strrpos($str, $find, $offset, $encoding); @@ -210,11 +210,11 @@ public static function prettifyFieldName(string $field): string /** * @param string $scene Current scene value - * @param string|array $ruleOn + * @param array|string $ruleOn * * @return bool */ - public static function ruleIsAvailable(string $scene, $ruleOn): bool + public static function ruleIsAvailable(string $scene, array|string $ruleOn): bool { // - rule is not limit scene if (!$ruleOn) { @@ -228,7 +228,7 @@ public static function ruleIsAvailable(string $scene, $ruleOn): bool return false; } - $scenes = is_string($ruleOn) ? Filters::explode($ruleOn) : (array)$ruleOn; + $scenes = is_string($ruleOn) ? Filters::explode($ruleOn) : $ruleOn; return in_array($scene, $scenes, true); } @@ -236,13 +236,13 @@ public static function ruleIsAvailable(string $scene, $ruleOn): bool /** * getValueOfArray 支持以 '.' 分割进行子级值获取 eg: 'goods.apple' * - * @param array $array - * @param array|string $key - * @param mixed $default + * @param array $array + * @param array|string|null $key + * @param mixed|null $default * * @return mixed */ - public static function getValueOfArray(array $array, $key, $default = null) + public static function getValueOfArray(array $array, array|string|null $key, mixed $default = null): mixed { if (null === $key) { return $array; @@ -276,7 +276,7 @@ public static function getValueOfArray(array $array, $key, $default = null) * @return mixed * @throws InvalidArgumentException */ - public static function call($cb, ...$args) + public static function call(mixed $cb, ...$args): mixed { if (is_string($cb)) { // className::method @@ -305,13 +305,13 @@ public static function call($cb, ...$args) * - string Compare length * - array Compare length * - * @param mixed $val - * @param mixed $expected + * @param int|string|array $val * @param string $operator + * @param int|string|array $expected * * @return bool */ - public static function compareSize($val, string $operator, $expected): bool + public static function compareSize(int|string|array $val, string $operator, int|string|array $expected): bool { // type must be same if (gettype($val) !== gettype($expected)) { @@ -351,7 +351,7 @@ public static function compareSize($val, string $operator, $expected): bool * * @return bool */ - public static function inArray($val, array $list): bool + public static function inArray(mixed $val, array $list): bool { if (!is_scalar($val)) { return false; diff --git a/src/Locale/LocaleZhCN.php b/src/Locale/LocaleZhCN.php index 0c5664a..1311e77 100644 --- a/src/Locale/LocaleZhCN.php +++ b/src/Locale/LocaleZhCN.php @@ -16,7 +16,7 @@ class LocaleZhCN * * @var array */ - public static $messages = [ + public static array $messages = [ // 'int' 'integer' 'integer' => [ '{attr} 必须是整数!', diff --git a/src/Simple/ValidData.php b/src/Simple/ValidData.php index f4640ee..b4ae89c 100644 --- a/src/Simple/ValidData.php +++ b/src/Simple/ValidData.php @@ -26,18 +26,18 @@ class ValidData /** * @var array */ - protected static $data = []; + protected static array $data = []; /** * @var int */ - private static $throwCode = 404; + private static int $throwCode = 404; /** * @var string * @psalm-var class-string */ - private static $throwClass = ValidateException::class; + private static string $throwClass = ValidateException::class; /** * @param array $data @@ -338,7 +338,7 @@ public static function getArrayByJSON(string $field, int $min = null, int $max = throw self::newEx($field, 'must be valid JSON string'); } - $arr = json_decode($val, true); + $arr = json_decode($val, true, 512, JSON_THROW_ON_ERROR); if (json_last_error() !== JSON_ERROR_NONE) { throw self::newEx($field, 'must be valid JSON string'); } diff --git a/src/Simple/ValidValue.php b/src/Simple/ValidValue.php index bc943c9..55d08c1 100644 --- a/src/Simple/ValidValue.php +++ b/src/Simple/ValidValue.php @@ -14,12 +14,12 @@ class ValidValue /** * @var int */ - private static $throwCode = 404; + private static int $throwCode = 404; /** * @var string */ - private static $throwClass = InvalidArgumentException::class; + private static string $throwClass = InvalidArgumentException::class; /** * Validate and return valid string @@ -40,7 +40,7 @@ class ValidValue */ public static function getString(string $value, ?int $min, ?int $max, array $opt = []): string { - + return ''; } /** diff --git a/src/Traits/ErrorMessageTrait.php b/src/Traits/ErrorMessageTrait.php index a6ec885..97e612d 100644 --- a/src/Traits/ErrorMessageTrait.php +++ b/src/Traits/ErrorMessageTrait.php @@ -2,7 +2,6 @@ namespace Inhere\Validate\Traits; -use Closure; use Inhere\Validate\Helper; use Inhere\Validate\Validator\GlobalMessage; use Inhere\Validate\Validators; @@ -14,7 +13,6 @@ use function is_array; use function is_int; use function is_string; -use function strpos; use function strtr; /** @@ -30,25 +28,26 @@ trait ErrorMessageTrait * * @var array */ - private $_messages = []; + private array $_messages = []; /** * attribute field translate list * * @var array */ - private $_translates = []; + private array $_translates = []; /** * Save all validation error messages * + * [ + * ['name' => 'field', 'msg' => 'error Message1' ], + * ['name' => 'field2', 'msg' => 'error Message2' ], + * ] + * * @var array[] - * [ - * ['name' => 'field', 'msg' => 'error Message1' ], - * ['name' => 'field2', 'msg' => 'error Message2' ], - * ] */ - private $_errors = []; + private array $_errors = []; /** * Whether there is error stop validation 是否出现验证失败就立即停止验证 @@ -57,14 +56,14 @@ trait ErrorMessageTrait * * @var boolean */ - private $_stopOnError = true; + private bool $_stopOnError = true; /** * Prettify field name on get error message * * @var bool */ - private $_prettifyName = true; + private bool $_prettifyName = true; protected function prepareValidation(): void { @@ -211,7 +210,7 @@ public function clearErrors(): void * * @return array|string */ - public function firstError(bool $onlyMsg = true) + public function firstError(bool $onlyMsg = true): array|string { if (!$errors = $this->_errors) { return $onlyMsg ? '' : []; @@ -228,7 +227,7 @@ public function firstError(bool $onlyMsg = true) * * @return array|string */ - public function lastError(bool $onlyMsg = true) + public function lastError(bool $onlyMsg = true): array|string { if (!$errors = $this->_errors) { return $onlyMsg ? '' : []; @@ -239,16 +238,15 @@ public function lastError(bool $onlyMsg = true) } /** - * @param bool|mixed|null $_stopOnError + * @param mixed|null $_stopOnError * - * @return $this + * @return static */ - public function setStopOnError($_stopOnError = null): self + public function setStopOnError(mixed $_stopOnError = null): static { if (null !== $_stopOnError) { $this->_stopOnError = (bool)$_stopOnError; } - return $this; } @@ -266,9 +264,9 @@ public function isStopOnError(): bool /** * @param string $key - * @param string|array $message + * @param array|string $message */ - public function setMessage(string $key, $message): void + public function setMessage(string $key, array|string $message): void { if ($key && $message) { $this->_messages[$key] = $message; @@ -286,9 +284,9 @@ public function getMessages(): array /** * @param array $messages * - * @return $this + * @return static */ - public function setMessages(array $messages): self + public function setMessages(array $messages): static { foreach ($messages as $key => $value) { $this->setMessage($key, $value); @@ -299,14 +297,14 @@ public function setMessages(array $messages): self /** * 各个验证器的提示消息 * - * @param string|Closure $validator 验证器 + * @param callable|string $validator 验证器 * @param string $field * @param array $args - * @param string|array|null $message 自定义提示消息 + * @param array|string|null $message 自定义提示消息 * * @return string */ - public function getMessage($validator, string $field, array $args = [], $message = null): string + public function getMessage(callable|string $validator, string $field, array $args = [], array|string $message = null): string { $rawName = is_string($validator) ? $validator : 'callback'; $params = [ @@ -318,17 +316,11 @@ public function getMessage($validator, string $field, array $args = [], $message $message = $this->findMessage($field, $rawName) ?: GlobalMessage::getDefault(); // is array. It's defined multi error messages } elseif (is_array($message)) { - if (isset($message[$field])) { - $message = $message[$field]; - } else { - $message = $message[$rawName] ?? $this->findMessage($field, $rawName); - } + $message = $message[$field] ?? $message[$rawName] ?? $this->findMessage($field, $rawName); if (!$message) { // use default return strtr(GlobalMessage::getDefault(), $params); } - } else { - $message = (string)$message; } /** @see GlobalMessage::$messages['size'] */ @@ -337,12 +329,12 @@ public function getMessage($validator, string $field, array $args = [], $message $message = $message[$msgKey] ?? $message[0]; } - if (false === strpos($message, '{')) { + if (!str_contains($message, '{')) { return $message; } foreach ($args as $key => $value) { - $key = is_int($key) ? "value{$key}" : $key; + $key = is_int($key) ? "value$key" : $key; // build params $params['{' . $key . '}'] = is_array($value) ? implode(',', $value) : $value; } @@ -356,7 +348,7 @@ public function getMessage($validator, string $field, array $args = [], $message * * @return string|array */ - protected function findMessage(string $field, string $rawName) + protected function findMessage(string $field, string $rawName): array|string { // allow define a message for a validator. // eg: 'username.required' => 'some message ...' @@ -387,9 +379,9 @@ protected function findMessage(string $field, string $rawName) * * @param array $fieldTrans * - * @return $this + * @return static */ - public function setTranslates(array $fieldTrans): self + public function setTranslates(array $fieldTrans): static { return $this->addTranslates($fieldTrans); } @@ -399,9 +391,9 @@ public function setTranslates(array $fieldTrans): self * * @param array $fieldTrans * - * @return $this + * @return static */ - public function addTranslates(array $fieldTrans): self + public function addTranslates(array $fieldTrans): static { foreach ($fieldTrans as $field => $tran) { $this->_translates[$field] = $tran; diff --git a/src/Traits/MultipleRulesTrait.php b/src/Traits/MultipleRulesTrait.php index 483607b..c363847 100644 --- a/src/Traits/MultipleRulesTrait.php +++ b/src/Traits/MultipleRulesTrait.php @@ -101,7 +101,7 @@ protected function collectRules(): ?Generator protected function parseRule(string $rule, array $row): array { $rule = trim($rule, ': '); - if (false === strpos($rule, ':')) { + if (!str_contains($rule, ':')) { $row[0] = $rule; return $row; } diff --git a/src/Traits/ScopedValidatorsTrait.php b/src/Traits/ScopedValidatorsTrait.php index a689ab3..a4d8b2c 100644 --- a/src/Traits/ScopedValidatorsTrait.php +++ b/src/Traits/ScopedValidatorsTrait.php @@ -19,7 +19,6 @@ use function is_object; use function is_string; use function method_exists; -use function strpos; use function strrchr; use function strtolower; use function trim; @@ -35,13 +34,13 @@ trait ScopedValidatorsTrait { /** @var array user custom add's validators(current scope) */ - protected $_validators = []; + protected array $_validators = []; /** * @see $_FILES * @var array[] */ - private $uploadedFiles = []; + private array $uploadedFiles = []; /******************************************************************************* * custom validators @@ -159,14 +158,14 @@ public function clearValidators(): void * The verification field must exist and the input data is not empty. * * @param string $field - * @param null|mixed $value + * @param mixed|null $value * * @return bool * - True field exists and value is not empty. * - False field not exists or value is empty. * @see Validators::isEmpty() 如何鉴定为空 */ - public function required(string $field, $value = null): bool + public function required(string $field, mixed $value = null): bool { if (null !== $value) { $val = $value; @@ -185,17 +184,19 @@ public function required(string $field, $value = null): bool /** * 如果指定的另一个字段( anotherField )值等于任何一个 value 时,此字段为 必填 (refer laravel) * + * returns: + * - TRUE check successful + * - FALSE check failed + * - NULL skip check the field + * * @param string $field * @param mixed $fieldVal * @param string $anotherField - * @param array|string $values + * @param array|string|int $values * * @return bool|null - * - TRUE check successful - * - FALSE check failed - * - NULL skip check the field */ - public function requiredIf(string $field, $fieldVal, string $anotherField, $values): ?bool + public function requiredIf(string $field, mixed $fieldVal, string $anotherField, array|string|int $values): ?bool { if (isset($this->data[$anotherField])) { $anotherVal = $this->data[$anotherField]; @@ -220,7 +221,7 @@ public function requiredIf(string $field, $fieldVal, string $anotherField, $valu * @return bool|null * @see requiredIf() */ - public function requiredUnless(string $field, $fieldVal, string $anotherField, $values): ?bool + public function requiredUnless(string $field, mixed $fieldVal, string $anotherField, array|string $values): ?bool { if (isset($this->data[$anotherField])) { $anotherVal = $this->data[$anotherField]; @@ -244,7 +245,7 @@ public function requiredUnless(string $field, $fieldVal, string $anotherField, $ * @return bool|null * @see requiredIf() */ - public function requiredWith(string $field, $fieldVal, $fields): ?bool + public function requiredWith(string $field, mixed $fieldVal, array|string $fields): ?bool { foreach ((array)$fields as $name) { if ($this->required($name)) { @@ -265,7 +266,7 @@ public function requiredWith(string $field, $fieldVal, $fields): ?bool * @return bool|null * @see requiredIf() */ - public function requiredWithAll(string $field, $fieldVal, $fields): ?bool + public function requiredWithAll(string $field, mixed $fieldVal, array|string $fields): ?bool { $allHasValue = true; @@ -289,7 +290,7 @@ public function requiredWithAll(string $field, $fieldVal, $fields): ?bool * @return bool|null * @see requiredIf() */ - public function requiredWithout(string $field, $fieldVal, $fields): ?bool + public function requiredWithout(string $field, mixed $fieldVal, array|string $fields): ?bool { $allHasValue = true; @@ -313,7 +314,7 @@ public function requiredWithout(string $field, $fieldVal, $fields): ?bool * @return bool|null * @see requiredIf() */ - public function requiredWithoutAll(string $field, $fieldVal, $fields): ?bool + public function requiredWithoutAll(string $field, mixed $fieldVal, array|string $fields): ?bool { $allNoValue = true; @@ -335,11 +336,11 @@ public function requiredWithoutAll(string $field, $fieldVal, $fields): ?bool * 验证的字段必须是成功上传的文件 * * @param string $field - * @param string|array $suffixes e.g ['jpg', 'jpeg', 'png', 'gif', 'bmp'] + * @param array|string|null $suffixes e.g ['jpg', 'jpeg', 'png', 'gif', 'bmp'] * * @return bool */ - public function fileValidator(string $field, $suffixes = null): bool + public function fileValidator(string $field, array|string $suffixes = null): bool { if (!$file = $this->uploadedFiles[$field] ?? null) { return false; @@ -357,7 +358,7 @@ public function fileValidator(string $field, $suffixes = null): bool return false; } - $suffixes = is_string($suffixes) ? Filters::explode($suffixes) : (array)$suffixes; + $suffixes = is_string($suffixes) ? Filters::explode($suffixes) : $suffixes; return in_array(strtolower($suffix), $suffixes, true); } @@ -366,11 +367,11 @@ public function fileValidator(string $field, $suffixes = null): bool * 验证的字段必须是成功上传的图片文件 * * @param string $field - * @param string|array $suffixes e.g ['jpg', 'jpeg', 'png', 'gif', 'bmp'] + * @param array|string|null $suffixes e.g ['jpg', 'jpeg', 'png', 'gif', 'bmp'] * * @return bool */ - public function imageValidator(string $field, $suffixes = null): bool + public function imageValidator(string $field, array|string $suffixes = null): bool { if (!$file = $this->uploadedFiles[$field] ?? null) { return false; @@ -402,7 +403,7 @@ public function imageValidator(string $field, $suffixes = null): bool } $suffix = Helper::getImageExtByMime($mime); - $suffixes = is_string($suffixes) ? Filters::explode($suffixes) : (array)$suffixes; + $suffixes = is_string($suffixes) ? Filters::explode($suffixes) : $suffixes; return in_array($suffix, $suffixes, true); } @@ -415,11 +416,11 @@ public function imageValidator(string $field, $suffixes = null): bool * ['video', 'mimeTypes', 'video/avi,video/mpeg,video/quicktime'] * * @param string $field - * @param string|array $types + * @param array|string $types * * @return bool */ - public function mimeTypesValidator(string $field, $types): bool + public function mimeTypesValidator(string $field, array|string $types): bool { if (!$file = $this->uploadedFiles[$field] ?? null) { return false; @@ -444,12 +445,12 @@ public function mimeTypesValidator(string $field, $types): bool * ['photo', 'mimes', 'jpeg,bmp,png'] * * @param string $field - * @param string|array $types + * @param array|string|null $types * return bool * * @todo */ - public function mimesValidator(string $field, $types = null): void + public function mimesValidator(string $field, array|string $types = null): void { } @@ -465,7 +466,7 @@ public function mimesValidator(string $field, $types = null): void * * @return bool */ - public function compareValidator($val, string $compareField): bool + public function compareValidator(mixed $val, string $compareField): bool { return $compareField && ($val === $this->getByPath($compareField)); } @@ -483,7 +484,7 @@ public function eqFieldValidator($val, string $compareField): bool * * @return bool */ - public function neqFieldValidator($val, string $compareField): bool + public function neqFieldValidator(mixed $val, string $compareField): bool { return $compareField && ($val !== $this->getByPath($compareField)); } @@ -491,12 +492,12 @@ public function neqFieldValidator($val, string $compareField): bool /** * 字段值比较:当前字段值 要小于 给定字段的值 * - * @param string|int $val + * @param int|string $val * @param string $compareField * * @return bool */ - public function ltFieldValidator($val, string $compareField): bool + public function ltFieldValidator(int|string $val, string $compareField): bool { $maxVal = $this->getByPath($compareField); @@ -510,12 +511,12 @@ public function ltFieldValidator($val, string $compareField): bool /** * 字段值比较:当前字段值 要小于等于 给定字段的值 * - * @param string|int $val + * @param int|string $val * @param string $compareField * * @return bool */ - public function lteFieldValidator($val, string $compareField): bool + public function lteFieldValidator(int|string $val, string $compareField): bool { $maxVal = $this->getByPath($compareField); @@ -529,12 +530,12 @@ public function lteFieldValidator($val, string $compareField): bool /** * 字段值比较:当前字段值 要大于 给定字段的值 * - * @param string|int $val + * @param int|string $val * @param string $compareField * * @return bool */ - public function gtFieldValidator($val, string $compareField): bool + public function gtFieldValidator(int|string $val, string $compareField): bool { $minVal = $this->getByPath($compareField); @@ -548,12 +549,12 @@ public function gtFieldValidator($val, string $compareField): bool /** * 字段值比较:当前字段值 要大于等于 给定字段的值 * - * @param string|int $val + * @param int|string $val * @param string $compareField * * @return bool */ - public function gteFieldValidator($val, string $compareField): bool + public function gteFieldValidator(int|string $val, string $compareField): bool { $minVal = $this->getByPath($compareField); @@ -572,7 +573,7 @@ public function gteFieldValidator($val, string $compareField): bool * * @return bool */ - public function inFieldValidator($val, string $anotherField): bool + public function inFieldValidator(mixed $val, string $anotherField): bool { if ($anotherField && $dict = $this->getByPath($anotherField)) { return Validators::in($val, $dict); @@ -591,7 +592,7 @@ public function inFieldValidator($val, string $anotherField): bool * * @todo */ - public function intervalDayValidator($val, string $compareField, int $expected, string $op = '>='): void + public function intervalDayValidator(string $val, string $compareField, int $expected, string $op = '>='): void { } @@ -601,7 +602,7 @@ public function intervalDayValidator($val, string $compareField, int $expected, * `['goods.*', 'each', 'string']` * * @param array $values - * @param array ...$args + * @param mixed ...$args * - string|\Closure $validator * - ... args for $validator * @@ -658,7 +659,7 @@ public function eachValidator(array $values, ...$args): bool */ public static function isCheckFile(string $name): bool { - return false !== strpos(Helper::$fileValidators, '|' . $name . '|'); + return str_contains(Helper::$fileValidators, '|' . $name . '|'); } /** @@ -670,8 +671,8 @@ public static function isCheckRequired(string $name, array $args = []): bool { // the $arg.0 is validator name. $name = $name === 'each' ? ((string)($args[0] ?? '')) : $name; - - return 0 === strpos($name, 'required'); + + return str_starts_with($name, 'required'); } /** @@ -695,11 +696,11 @@ public function getUploadedFiles(): array /** * @param array $uploadedFiles * - * @return $this + * @return static */ - public function setUploadedFiles($uploadedFiles): self + public function setUploadedFiles(array $uploadedFiles): static { - $this->uploadedFiles = (array)$uploadedFiles; + $this->uploadedFiles = $uploadedFiles; return $this; } } diff --git a/src/ValidateException.php b/src/ValidateException.php deleted file mode 100644 index 15c74b6..0000000 --- a/src/ValidateException.php +++ /dev/null @@ -1,13 +0,0 @@ -traitGet($key, $value); } diff --git a/src/ValidationInterface.php b/src/ValidationInterface.php index b17d539..d87c657 100644 --- a/src/ValidationInterface.php +++ b/src/ValidationInterface.php @@ -1,13 +1,11 @@ _beforeHandler = $cb; return $this; @@ -171,9 +170,9 @@ public function beforeValidate(): bool * * @param Closure $cb * - * @return $this + * @return static */ - public function onAfterValidate(Closure $cb): self + public function onAfterValidate(Closure $cb): static { $this->_afterHandler = $cb; return $this; @@ -197,10 +196,9 @@ public function afterValidate(): void * @param array $onlyChecked You can set this field that needs verification * @param bool|null $stopOnError Stop verification if there is an error * - * @return $this - * @throws InvalidArgumentException + * @return static */ - public function validate(array $onlyChecked = [], bool $stopOnError = null): self + public function validate(array $onlyChecked = [], bool $stopOnError = null): static { if (!property_exists($this, 'data')) { throw new InvalidArgumentException('Must be defined property "data"(array) in the sub-class used.'); @@ -250,14 +248,14 @@ public function validate(array $onlyChecked = [], bool $stopOnError = null): sel /** * apply validate rule for given fields * - * @param string|array $fields + * @param array|string $fields * @param array $rule * @param array $onlyChecked * @param bool $stopOnError */ - protected function applyRule($fields, array $rule, array $onlyChecked, bool $stopOnError): void + protected function applyRule(array|string $fields, array $rule, array $onlyChecked, bool $stopOnError): void { - $fields = is_string($fields) ? Filters::explode($fields) : (array)$fields; + $fields = is_string($fields) ? Filters::explode($fields) : $fields; $validator = array_shift($rule); // How to determine the property is empty(default use the Validators::isEmpty) @@ -276,7 +274,7 @@ protected function applyRule($fields, array $rule, array $onlyChecked, bool $sto $skipOnEmpty = $rule['skipOnEmpty'] ?? $this->_skipOnEmpty; $filters = $rule['filter'] ?? null; // filter - $defMsg = $rule['msg'] ?? null; // Custom error message + $defMsg = $rule['msg'] ?? ''; // Custom error message $defValue = $rule['default'] ?? null; // Allow default $before = $rule['before'] ?? null; // Before validate function $after = $rule['after'] ?? null; // After validate function @@ -349,19 +347,21 @@ protected function applyRule($fields, array $rule, array $onlyChecked, bool $sto /** * field require/exists validate 字段存在检查 * + * returns: + * - TRUE check successful + * - FALSE check failed + * - NULL skip check(for `required*`) + * * @param string $field Attribute name * @param mixed $value Attribute value * @param string $validator required* Validator name * @param array $args Verify the required parameters - * @param string|array $defMsg + * @param array|string $defMsg * * @return bool|null - * - TRUE check successful - * - FALSE check failed - * - NULL skip check(for `required*`) * @throws InvalidArgumentException */ - protected function fieldValidate(string $field, $value, string $validator, array $args, $defMsg): ?bool + protected function fieldValidate(string $field, mixed $value, string $validator, array $args, array|string $defMsg): ?bool { // required check if ($validator === 'required') { @@ -402,12 +402,12 @@ protected function fieldValidate(string $field, $value, string $validator, array * @param mixed $value Field value * @param Closure|string|mixed $validator Validator * @param array $args Arguments for validate - * @param string|array $defMsg + * @param array|string $defMsg * * @return bool * @throws InvalidArgumentException */ - protected function valueValidate(string $field, $value, $validator, array $args, $defMsg): bool + protected function valueValidate(string $field, mixed $value, mixed $validator, array $args, array|string $defMsg): bool { // if field don't exist. if (null === $value) { @@ -470,11 +470,11 @@ protected function valueValidate(string $field, $value, $validator, array $args, * @param string $field * @param mixed $value */ - protected function collectSafeValue(string $field, $value): void + protected function collectSafeValue(string $field, mixed $value): void { // 进行的是子级属性检查 eg: 'goods.apple' if ($pos = strpos($field, '.')) { - $field = (string)substr($field, 0, $pos); + $field = substr($field, 0, $pos); $value = $this->getRaw($field, []); } @@ -596,11 +596,11 @@ public function getSceneFields(): array * 支持以 '.' 分割进行子级值获取 eg: $this->get('goods.apple') * * @param string $key The data key - * @param mixed $default The default value + * @param mixed|null $default The default value * * @return mixed The key's value, or the default value */ - public function getByPath(string $key, $default = null) + public function getByPath(string $key, mixed $default = null): mixed { if (isset($this->_dataCaches[$key])) { return $this->_dataCaches[$key]; @@ -623,12 +623,12 @@ public function getByPath(string $key, $default = null) /** * @param string $path 'users.*.id' 'goods.*' 'foo.bar.*.id' - * @param null|mixed $default + * @param mixed|null $default * @param array $data * * @return mixed */ - protected function getByWildcard(string $path, $default = null, array $data = []) + protected function getByWildcard(string $path, mixed $default = null, array $data = []): mixed { $data = $data ?: $this->data; @@ -709,9 +709,9 @@ public function getRules(): array /** * @param array $rules * - * @return $this + * @return static */ - public function setRules(array $rules): self + public function setRules(array $rules): static { $this->_rules = $rules; return $this; @@ -736,9 +736,9 @@ public function getScene(): string /** * @param string $scene * - * @return $this + * @return static */ - public function atScene(string $scene): self + public function atScene(string $scene): static { $this->scene = trim($scene); return $this; @@ -749,9 +749,9 @@ public function atScene(string $scene): self * * @param string $scene * - * @return $this|mixed + * @return static */ - public function setScene(string $scene) + public function setScene(string $scene): static { return $this->atScene($scene); } @@ -761,9 +761,9 @@ public function setScene(string $scene) * * @param string $scene * - * @return $this|mixed + * @return static */ - public function onScene(string $scene) + public function onScene(string $scene): static { return $this->atScene($scene); } @@ -771,9 +771,9 @@ public function onScene(string $scene) /** * @param bool $_skipOnEmpty * - * @return $this + * @return static */ - public function setSkipOnEmpty(bool $_skipOnEmpty): self + public function setSkipOnEmpty(bool $_skipOnEmpty): static { $this->_skipOnEmpty = $_skipOnEmpty; return $this; @@ -805,22 +805,22 @@ public function has(string $key): bool * Get data item by key * * @param string $key The data key - * @param mixed $default The default value to return if data key does not exist + * @param mixed|null $default The default value to return if data key does not exist * * @return mixed The key's value, or the default value */ - public function get(string $key, $default = null) + public function get(string $key, mixed $default = null): mixed { return $this->has($key) ? $this->data[$key] : $default; } /** * @param string $key - * @param null $default + * @param mixed|null $default * * @return mixed */ - public function getRaw(string $key, $default = null) + public function getRaw(string $key, mixed $default = null): mixed { return $this->has($key) ? $this->data[$key] : $default; } @@ -831,9 +831,9 @@ public function getRaw(string $key, $default = null) * @param string $key The data key * @param mixed $value The data value * - * @return $this + * @return static */ - public function setRaw(string $key, $value): self + public function setRaw(string $key, mixed $value): static { $this->data[$key] = $value; return $this; @@ -843,11 +843,11 @@ public function setRaw(string $key, $value): self * alias of the setRow() * * @param string $key - * @param $value + * @param mixed $value * - * @return $this|mixed + * @return static */ - public function setValue(string $key, $value) + public function setValue(string $key, mixed $value): static { return $this->setRaw($key, $value); } @@ -856,24 +856,11 @@ public function setValue(string $key, $value) * alias of the 'getSafe()' * * @param string $key - * @param mixed $default - * - * @return mixed - */ - public function val(string $key, $default = null) - { - return $this->getSafe($key, $default); - } - - /** - * alias of the 'getSafe()' - * - * @param string $key - * @param mixed $default + * @param mixed|null $default * * @return mixed */ - public function safe(string $key, $default = null) + public function val(string $key, mixed $default = null): mixed { return $this->getSafe($key, $default); } @@ -882,11 +869,11 @@ public function safe(string $key, $default = null) * get safe field value * * @param string $key - * @param mixed $default + * @param mixed|null $default * * @return mixed */ - public function getSafe(string $key, $default = null) + public function getSafe(string $key, mixed $default = null): mixed { return $this->_safeData[$key] ?? $default; } @@ -895,7 +882,7 @@ public function getSafe(string $key, $default = null) * @param string $key * @param mixed $value */ - public function setSafe(string $key, $value): void + public function setSafe(string $key, mixed $value): void { $this->_safeData[$key] = $value; } @@ -903,19 +890,9 @@ public function setSafe(string $key, $value): void /** * @param bool $asObject * - * @return array|stdClass - */ - public function safeData(bool $asObject = false) - { - return $this->getSafeData($asObject); - } - - /** - * @param bool $asObject - * - * @return array|stdClass + * @return array|object */ - public function getSafeData(bool $asObject = false) + public function getSafeData(bool $asObject = false): object|array { return $asObject ? (object)$this->_safeData : $this->_safeData; } diff --git a/src/Validator/AbstractValidator.php b/src/Validator/AbstractValidator.php index 823b1ab..addd534 100644 --- a/src/Validator/AbstractValidator.php +++ b/src/Validator/AbstractValidator.php @@ -4,6 +4,7 @@ /** * Class AbstractValidator + * * @package Inhere\Validate\Validator */ abstract class AbstractValidator implements ValidatorInterface @@ -16,7 +17,7 @@ abstract class AbstractValidator implements ValidatorInterface * * @return bool */ - public function __invoke($value, array $data): bool + public function __invoke(mixed $value, array $data): bool { return $this->validate($value, $data); } diff --git a/src/Validator/GlobalMessage.php b/src/Validator/GlobalMessage.php index 173b89a..4db1dd0 100644 --- a/src/Validator/GlobalMessage.php +++ b/src/Validator/GlobalMessage.php @@ -13,7 +13,7 @@ final class GlobalMessage * * @var array */ - public static $messages = [ + public static array $messages = [ // 'int' 'integer' 'integer' => [ '{attr} must be an integer!', @@ -118,16 +118,16 @@ final class GlobalMessage * * @return string|array */ - public static function get(string $key) + public static function get(string $key): array|string { return self::$messages[$key] ?? ''; } /** * @param string $key - * @param string|array $msg + * @param array|string $msg */ - public static function set(string $key, $msg): void + public static function set(string $key, array|string $msg): void { if ($key && $msg) { self::$messages[$key] = $msg; diff --git a/src/Validator/UserValidators.php b/src/Validator/UserValidators.php index ee793a7..3fcdc6e 100644 --- a/src/Validator/UserValidators.php +++ b/src/Validator/UserValidators.php @@ -20,7 +20,7 @@ final class UserValidators /** * @var array user custom added validators (global) */ - private static $validators = []; + private static array $validators = []; /** * add a custom validator diff --git a/src/Validator/ValidatorInterface.php b/src/Validator/ValidatorInterface.php index d35443f..65addab 100644 --- a/src/Validator/ValidatorInterface.php +++ b/src/Validator/ValidatorInterface.php @@ -15,5 +15,5 @@ interface ValidatorInterface * * @return bool */ - public function validate($value, array $data): bool; + public function validate(mixed $value, array $data): bool; } diff --git a/src/Validators.php b/src/Validators.php index d6fab0b..f20ad97 100644 --- a/src/Validators.php +++ b/src/Validators.php @@ -12,6 +12,7 @@ use Inhere\Validate\Exception\ArrayValueNotExists; use Inhere\Validate\Traits\NameAliasTrait; +use JsonException; use function array_diff; use function array_key_exists; use function array_keys; @@ -34,7 +35,6 @@ use function is_string; use function json_decode; use function json_last_error; -use function method_exists; use function preg_match; use function stripos; use function strpos; @@ -70,7 +70,7 @@ class Validators /** * @var array */ - private static $aliases = [ + private static array $aliases = [ // alias => real name. 'int' => 'integer', 'num' => 'number', @@ -121,7 +121,7 @@ class Validators * * @return bool */ - public static function isEmpty($val): bool + public static function isEmpty(mixed $val): bool { if (is_string($val)) { $val = trim($val); @@ -158,7 +158,7 @@ public static function isEmpty($val): bool * * @return bool */ - public static function boolean($val): bool + public static function boolean(mixed $val): bool { if (!is_scalar($val)) { return false; @@ -178,7 +178,7 @@ public static function boolean($val): bool * @return bool * @see Validators::boolean() */ - public static function bool($val): bool + public static function bool(mixed $val): bool { return self::boolean($val); } @@ -186,18 +186,18 @@ public static function bool($val): bool /** * check value is float * - * @param mixed $val 要验证的变量 - * @param null|integer|float $min 最小值 - * @param null|int|float $max 最大值 + * @param mixed $val 要验证的变量 + * @param float|string|int|null $min 最小值 + * @param string|float|int|null $max 最大值 * $options = [ * 'default' => 'default value', * 'decimal' => 2 * ] - * @param int|mixed $flags FILTER_FLAG_ALLOW_THOUSAND + * @param string|int $flags FILTER_FLAG_ALLOW_THOUSAND * * @return bool */ - public static function float($val, $min = null, $max = null, $flags = 0): bool + public static function float(mixed $val, float|string|int $min = null, string|float|int $max = null, string|int $flags = 0): bool { if (!is_numeric($val)) { return false; @@ -239,10 +239,10 @@ public static function float($val, $min = null, $max = null, $flags = 0): bool /** * int 验证 (所有的最小、最大都是包含边界值的) * - * @param int|string $val 要验证的变量 - * @param null|int|string $min 最小值 - * @param null|int|string $max 最大值 - * @param int|string $flags 标志 + * @param mixed $val 要验证的变量 + * @param int|string|null $min 最小值 + * @param int|string|null $max 最大值 + * @param int|string $flags 标志 * FILTER_FLAG_ALLOW_OCTAL - 允许八进制数值 * FILTER_FLAG_ALLOW_HEX - 允许十六进制数值 * @@ -254,7 +254,7 @@ public static function float($val, $min = null, $max = null, $flags = 0): bool * // 'default' => 3, // value to return if the filter fails * ] */ - public static function integer($val, $min = null, $max = null, $flags = 0): bool + public static function integer(mixed $val, int|string $min = null, int|string $max = null, int|string $flags = 0): bool { if (!is_numeric($val)) { return false; @@ -290,15 +290,15 @@ public static function integer($val, $min = null, $max = null, $flags = 0): bool } /** - * @param int|mixed $val + * @param int|mixed $val * @param int|numeric|null $min * @param int|numeric|null $max - * @param int|mixed $flags + * @param string|int $flags * * @return bool * @see integer() */ - public static function int($val, $min = null, $max = null, $flags = 0): bool + public static function int(mixed $val, float|int|string $min = null, float|int|string $max = null, string|int $flags = 0): bool { return self::integer($val, $min, $max, $flags); } @@ -306,14 +306,14 @@ public static function int($val, $min = null, $max = null, $flags = 0): bool /** * check var is a integer and greater than 0 * - * @param mixed $val - * @param null|numeric|integer $min 最小值 - * @param null|numeric|int $max 最大值 - * @param int|mixed $flags + * @param mixed $val + * @param integer|numeric|null $min 最小值 + * @param int|numeric|null $max 最大值 + * @param string|int $flags * * @return bool */ - public static function number($val, $min = null, $max = null, $flags = 0): bool + public static function number(mixed $val, float|int|string $min = null, float|int|string $max = null, string|int $flags = 0): bool { if (!is_numeric($val)) { return false; @@ -327,15 +327,15 @@ public static function number($val, $min = null, $max = null, $flags = 0): bool } /** - * @param int|mixed $val + * @param int|mixed $val * @param int|numeric|null $min * @param int|numeric|null $max - * @param int|mixed $flags + * @param string|int $flags * * @return bool * @see number() */ - public static function num($val, $min = null, $max = null, $flags = 0): bool + public static function num(mixed $val, float|int|string $min = null, float|int|string $max = null, string|int $flags = 0): bool { return self::number($val, $min, $max, $flags); } @@ -343,13 +343,13 @@ public static function num($val, $min = null, $max = null, $flags = 0): bool /** * check val is a string * - * @param mixed $val - * @param int|numeric $minLen - * @param null|int|numeric $maxLen + * @param mixed $val + * @param int|numeric $minLen + * @param int|numeric|null $maxLen * * @return bool */ - public static function string($val, $minLen = 0, $maxLen = null): bool + public static function string(mixed $val, float|int|string $minLen = 0, float|int|string $maxLen = null): bool { if (!is_string($val)) { return false; @@ -372,7 +372,7 @@ public static function string($val, $minLen = 0, $maxLen = null): bool * * @return bool */ - public static function accepted($val): bool + public static function accepted(mixed $val): bool { if (!is_scalar($val)) { return false; @@ -388,7 +388,7 @@ public static function accepted($val): bool * * @return bool */ - public static function alpha($val): bool + public static function alpha(mixed $val): bool { return is_string($val) && preg_match('/^(?:[a-zA-Z]+)$/', $val) === 1; } @@ -400,7 +400,7 @@ public static function alpha($val): bool * * @return bool */ - public static function alphaNum($val): bool + public static function alphaNum(mixed $val): bool { if (!is_string($val) && !is_numeric($val)) { return false; @@ -416,7 +416,7 @@ public static function alphaNum($val): bool * * @return bool */ - public static function alphaDash($val): bool + public static function alphaDash(float|int|string $val): bool { if (!is_string($val) && !is_numeric($val)) { return false; @@ -443,28 +443,30 @@ public static function same($val, $expected): bool /** * Must be equal to the given value * - * @param mixed $val - * @param mixed $expected - * @param bool|mixed $strict + * @param mixed $val + * @param mixed $expected + * @param mixed|bool $strict * * @return bool */ - public static function eq($val, $expected, $strict = true): bool + public static function eq(mixed $val, mixed $expected, mixed $strict = true): bool { + /** @noinspection TypeUnsafeComparisonInspection */ return $strict ? $val === $expected : $val == $expected; } /** * Cannot be equal to a given value * - * @param mixed $val - * @param mixed $expected - * @param bool|mixed $strict + * @param mixed $val + * @param mixed $expected + * @param mixed $strict * * @return bool */ - public static function neq($val, $expected, $strict = true): bool + public static function neq(mixed $val, mixed $expected, mixed $strict = true): bool { + /** @noinspection TypeUnsafeComparisonInspection */ return $strict ? $val !== $expected : $val != $expected; } @@ -477,7 +479,7 @@ public static function neq($val, $expected, $strict = true): bool * @return bool * @see Helper::compareSize() */ - public static function gt($val, $expected): bool + public static function gt(mixed $val, mixed $expected): bool { return Helper::compareSize($val, '>', $expected); } @@ -490,7 +492,7 @@ public static function gt($val, $expected): bool * * @return bool */ - public static function gte($val, $expected): bool + public static function gte(mixed $val, mixed $expected): bool { return Helper::compareSize($val, '>=', $expected); } @@ -504,7 +506,7 @@ public static function gte($val, $expected): bool * @return bool * @see Helper::compareSize() */ - public static function lt($val, $expected): bool + public static function lt(mixed $val, mixed $expected): bool { return Helper::compareSize($val, '<', $expected); } @@ -517,7 +519,7 @@ public static function lt($val, $expected): bool * * @return bool */ - public static function lte($val, $expected): bool + public static function lte(mixed $val, mixed $expected): bool { return Helper::compareSize($val, '<=', $expected); } @@ -525,12 +527,12 @@ public static function lte($val, $expected): bool /** * 最小值检查 * - * @param int|string|array $val - * @param int|string $minRange + * @param array|int|string $val + * @param int|string $minRange * * @return bool */ - public static function min($val, $minRange): bool + public static function min(array|int|string $val, int|string $minRange): bool { return self::size($val, $minRange); } @@ -538,12 +540,12 @@ public static function min($val, $minRange): bool /** * 最大值检查 * - * @param int|string|array $val - * @param int|string $maxRange + * @param array|int|string $val + * @param int|string $maxRange * * @return bool */ - public static function max($val, $maxRange): bool + public static function max(array|int|string $val, int|string $maxRange): bool { return self::size($val, null, $maxRange); } @@ -556,13 +558,13 @@ public static function max($val, $maxRange): bool * 范围检查 * $min $max 即使传错位置也会自动调整 * - * @param int|float|string|array $val 待检测的值。 数字检查数字范围; 字符串、数组则检查长度 - * @param null|int|float|string $min 最小值 - * @param null|int|float|string $max 最大值 + * @param float|array|int|string $val 待检测的值。 数字检查数字范围; 字符串、数组则检查长度 + * @param float|int|string|null $min 最小值 + * @param float|int|string|null $max 最大值 * * @return bool */ - public static function size($val, $min = null, $max = null): bool + public static function size(float|array|int|string $val, float|int|string $min = null, float|int|string $max = null): bool { if (!is_numeric($val)) { if (is_string($val)) { @@ -580,27 +582,27 @@ public static function size($val, $min = null, $max = null): bool } /** - * @param int|string|array|mixed $val - * @param int|string|null $min - * @param int|string|null $max + * @param float|array|int|string $val + * @param int|string|null $min + * @param int|string|null $max * * @return bool * @see Validators::size() */ - public static function between($val, $min = null, $max = null): bool + public static function between(float|array|int|string $val, int|string $min = null, int|string $max = null): bool { return self::size($val, $min, $max); } /** - * @param int|string|array|mixed $val - * @param int|null $min - * @param int|null $max + * @param float|array|int|string $val + * @param int|string|null $min + * @param int|string|null $max * * @return bool * @see Validators::size() */ - public static function range($val, $min = null, $max = null): bool + public static function range(float|array|int|string $val, int|string $min = null, int|string $max = null): bool { return self::size($val, $min, $max); } @@ -608,13 +610,13 @@ public static function range($val, $min = null, $max = null): bool /** * 字符串/数组长度检查 * - * @param string|array $val 字符串/数组 - * @param int|numeric $minLen 最小长度 - * @param int|numeric $maxLen 最大长度 + * @param array|string $val 字符串/数组 + * @param int|numeric $minLen 最小长度 + * @param int|numeric|null $maxLen 最大长度 * * @return bool */ - public static function length($val, $minLen = 0, $maxLen = null): bool + public static function length(array|string $val, float|int|string $minLen = 0, float|int|string $maxLen = null): bool { if (!is_string($val) && !is_array($val)) { return false; @@ -626,12 +628,12 @@ public static function length($val, $minLen = 0, $maxLen = null): bool /** * 固定的长度 * - * @param mixed $val + * @param mixed $val * @param int|numeric $size * * @return bool */ - public static function fixedSize($val, $size): bool + public static function fixedSize(mixed $val, float|int|string $size): bool { if (!is_int($val)) { if (is_string($val)) { @@ -647,23 +649,23 @@ public static function fixedSize($val, $size): bool } /** - * @param mixed $val + * @param mixed $val * @param int|numeric $size * * @return bool */ - public static function lengthEq($val, $size): bool + public static function lengthEq(mixed $val, float|int|string $size): bool { return self::fixedSize($val, $size); } /** - * @param mixed $val + * @param mixed $val * @param int|numeric $size * * @return bool */ - public static function sizeEq($val, $size): bool + public static function sizeEq(mixed $val, float|int|string $size): bool { return self::fixedSize($val, $size); } @@ -675,12 +677,12 @@ public static function sizeEq($val, $size): bool /** * 值是否包含给的数据 * - * @param string|mixed $val - * @param int|string|array $needle + * @param string|mixed $val + * @param array|int|string $needle * * @return bool */ - public static function contains($val, $needle): bool + public static function contains(mixed $val, array|int|string $needle): bool { if (!$val || !is_string($val)) { return false; @@ -691,7 +693,7 @@ public static function contains($val, $needle): bool } if (is_array($needle)) { - foreach ((array)$needle as $item) { + foreach ($needle as $item) { if (stripos($val, $item) !== false) { return true; } @@ -704,13 +706,13 @@ public static function contains($val, $needle): bool /** * 用正则验证数据 * - * @param string|numeric $val 要验证的数据 - * @param string $regexp 正则表达式 "/^M(.*)/" - * @param null $default + * @param string|numeric $val 要验证的数据 + * @param string $regexp 正则表达式 "/^M(.*)/" + * @param null $default * * @return bool */ - public static function regexp($val, string $regexp, $default = null): bool + public static function regexp(float|int|string $val, string $regexp, $default = null): bool { $options = [ 'regexp' => $regexp @@ -727,12 +729,12 @@ public static function regexp($val, string $regexp, $default = null): bool * alias of the 'regexp()' * * @param string|numeric $val - * @param string $regexp - * @param null $default + * @param string $regexp + * @param null $default * * @return bool */ - public static function regex($val, string $regexp, $default = null): bool + public static function regex(float|int|string $val, string $regexp, $default = null): bool { return self::regexp($val, $regexp, $default); } @@ -740,9 +742,9 @@ public static function regex($val, string $regexp, $default = null): bool /** * url地址验证 * - * @param string|mixed $val 要验证的数据 - * @param mixed $default 设置验证失败时返回默认值 - * @param int|numeric $flags 标志 + * @param string|mixed $val 要验证的数据 + * @param mixed|null $default 设置验证失败时返回默认值 + * @param int|numeric $flags 标志 * FILTER_FLAG_SCHEME_REQUIRED - 要求 URL 是 RFC 兼容 URL(比如 http://example) * FILTER_FLAG_HOST_REQUIRED - 要求 URL 包含主机名(比如 http://www.example.com) * FILTER_FLAG_PATH_REQUIRED - 要求 URL 在域名后存在路径(比如 www.example.com/example1/test2/) @@ -750,7 +752,7 @@ public static function regex($val, string $regexp, $default = null): bool * * @return bool */ - public static function url($val, $default = null, $flags = 0): bool + public static function url(mixed $val, mixed $default = null, float|int|string $flags = 0): bool { $settings = (int)$flags !== 0 ? ['flags' => (int)$flags] : []; @@ -764,12 +766,12 @@ public static function url($val, $default = null, $flags = 0): bool /** * email 地址验证 * - * @param string $val 要验证的数据 - * @param mixed $default 设置验证失败时返回默认值 + * @param string $val 要验证的数据 + * @param mixed|null $default 设置验证失败时返回默认值 * * @return bool */ - public static function email($val, $default = null): bool + public static function email(string $val, mixed $default = null): bool { $options = []; @@ -783,9 +785,9 @@ public static function email($val, $default = null): bool /** * IP 地址验证 * - * @param string|mixed $val 要验证的数据 - * @param mixed $default 设置验证失败时返回默认值 - * @param int|numeric $flags 标志 + * @param string|mixed $val 要验证的数据 + * @param mixed|null $default 设置验证失败时返回默认值 + * @param int|numeric $flags 标志 * FILTER_FLAG_IPV4 - 要求值是合法的 IPv4 IP(比如 255.255.255.255) * FILTER_FLAG_IPV6 - 要求值是合法的 IPv6 IP(比如 2001:0db8:85a3:08d3:1319:8a2e:0370:7334) * FILTER_FLAG_NO_PRIV_RANGE - 要求值不在 RFC 指定的私有范围 IP 内(比如 192.168.0.1) @@ -793,7 +795,7 @@ public static function email($val, $default = null): bool * * @return bool */ - public static function ip($val, $default = null, $flags = 0): bool + public static function ip(mixed $val, mixed $default = null, float|int|string $flags = 0): bool { if (!is_string($val)) { return false; @@ -815,7 +817,7 @@ public static function ip($val, $default = null, $flags = 0): bool * * @return bool */ - public static function ipv4($val): bool + public static function ipv4(mixed $val): bool { return self::ip($val, false, FILTER_FLAG_IPV4); } @@ -827,7 +829,7 @@ public static function ipv4($val): bool * * @return bool */ - public static function ipv6($val): bool + public static function ipv6(mixed $val): bool { return self::ip($val, false, FILTER_FLAG_IPV6); } @@ -839,7 +841,7 @@ public static function ipv6($val): bool * * @return bool */ - public static function macAddress($input): bool + public static function macAddress(mixed $input): bool { if (!is_string($input) || !$input) { return false; @@ -855,7 +857,7 @@ public static function macAddress($input): bool * * @return bool */ - public static function english($val): bool + public static function english(mixed $val): bool { if (!$val || !is_string($val)) { return false; @@ -867,22 +869,14 @@ public static function english($val): bool /** * 验证字段值是否是一个有效的 JSON 字符串。 * - * @param mixed $val - * @param bool|mixed $strict + * @param mixed $val + * @param string|int|bool $strict * * @return bool */ - public static function json($val, $strict = true): bool + public static function json(mixed $val, string|int|bool $strict = true): bool { - if (!$val) { - return false; - } - - if (is_object($val) && method_exists($val, '__toString')) { - $val = (string)$val; - } - - if (!is_string($val)) { + if (!$val || !is_string($val)) { return false; } @@ -891,7 +885,11 @@ public static function json($val, $strict = true): bool return false; } - json_decode($val, true); + try { + json_decode($val, true, 512, JSON_THROW_ON_ERROR); + } catch (JsonException $e) { + return false; + } return json_last_error() === JSON_ERROR_NONE; } @@ -906,7 +904,7 @@ public static function json($val, $strict = true): bool * * @return bool */ - public static function isArray($val): bool + public static function isArray(mixed $val): bool { return is_array($val); } @@ -918,7 +916,7 @@ public static function isArray($val): bool * * @return bool */ - public static function isMap($val): bool + public static function isMap(mixed $val): bool { if (!is_array($val)) { return false; @@ -935,7 +933,7 @@ public static function isMap($val): bool * * @return bool */ - public static function isList($val): bool + public static function isList(mixed $val): bool { if (!is_array($val) || !isset($val[0])) { return false; @@ -952,7 +950,7 @@ public static function isList($val): bool * * @return bool */ - public static function intList($val): bool + public static function intList(mixed $val): bool { if (!is_array($val) || !isset($val[0])) { return false; @@ -981,7 +979,7 @@ public static function intList($val): bool * * @return bool */ - public static function numList($val): bool + public static function numList(mixed $val): bool { if (!is_array($val) || !isset($val[0])) { return false; @@ -1010,7 +1008,7 @@ public static function numList($val): bool * * @return bool */ - public static function strList($val): bool + public static function strList(mixed $val): bool { if (!$val || !is_array($val)) { return false; @@ -1039,7 +1037,7 @@ public static function strList($val): bool * * @return bool */ - public static function arrList($val): bool + public static function arrList(mixed $val): bool { if (!$val || !is_array($val)) { return false; @@ -1055,12 +1053,12 @@ public static function arrList($val): bool } /** - * @param array|mixed $val - * @param string|int|array $key + * @param array|mixed $val + * @param array|int|string $key * * @return bool */ - public static function hasKey($val, $key): bool + public static function hasKey(mixed $val, array|int|string $key): bool { if (!$val || !is_array($val)) { return false; @@ -1087,7 +1085,7 @@ public static function hasKey($val, $key): bool * * @return bool */ - public static function distinct($val): bool + public static function distinct(mixed $val): bool { if (!$val || !is_array($val)) { return false; @@ -1097,44 +1095,44 @@ public static function distinct($val): bool } /** - * @param mixed $val + * @param mixed $val * @param array|string $dict - * @param bool|mixed $strict Use strict check, will check data type. + * @param bool|string|int $strict Use strict check, will check data type. * * @return bool */ - public static function enum($val, $dict, $strict = false): bool + public static function enum(mixed $val, array|string $dict, bool|string|int $strict = false): bool { if (is_string($dict)) { // $dict = array_map('trim', explode(',', $dict)); return false !== ($strict ? strpos($dict, (string)$val) : stripos($dict, (string)$val)); } - return in_array($val, (array)$dict, $strict); + return in_array($val, $dict, $strict); } /** * alias of 'enum()' * - * @param mixed $val + * @param mixed $val * @param array|string $dict - * @param bool|mixed $strict + * @param bool|string|int $strict * * @return bool */ - public static function in($val, $dict, $strict = false): bool + public static function in(mixed $val, array|string $dict, bool|string|int $strict = false): bool { return self::enum($val, $dict, $strict); } /** - * @param mixed $val + * @param mixed $val * @param array|string $dict - * @param bool|mixed $strict + * @param bool|string|int $strict * * @return bool */ - public static function notIn($val, $dict, $strict = false): bool + public static function notIn(mixed $val, array|string $dict, bool|string|int $strict = false): bool { if (is_string($dict) && strpos($dict, ',')) { $dict = array_map('trim', explode(',', $dict)); @@ -1148,13 +1146,13 @@ public static function notIn($val, $dict, $strict = false): bool ******************************************************************************/ /** - * @param mixed $val + * @param mixed $val * @param string|numeric $start - * @param bool|mixed $strict + * @param string|int|bool $strict * * @return bool */ - public static function startWith($val, $start, $strict = true): bool + public static function startWith(mixed $val, float|int|string $start, string|int|bool $strict = true): bool { if (($start = (string)$start) === '') { return false; @@ -1174,13 +1172,13 @@ public static function startWith($val, $start, $strict = true): bool } /** - * @param mixed $val + * @param mixed $val * @param string|numeric $end - * @param bool|mixed $strict + * @param string|int|bool $strict * * @return bool */ - public static function endWith($val, $end, $strict = true): bool + public static function endWith(mixed $val, float|int|string $end, string|int|bool $strict = true): bool { $last = null; $end = (string)$end; @@ -1204,11 +1202,11 @@ public static function endWith($val, $end, $strict = true): bool * 校验字段值是否是日期格式 * * @param string|mixed $val 日期 - * @param bool|string $sholdGt0 + * @param bool|string $shouldGt0 * * @return boolean */ - public static function date($val, $sholdGt0 = false): bool + public static function date(mixed $val, bool|string $shouldGt0 = false): bool { if (!$val) { return false; @@ -1217,7 +1215,7 @@ public static function date($val, $sholdGt0 = false): bool // strtotime 转换不对,日期格式显然不对 $time = strtotime((string)$val); - return $sholdGt0 ? $sholdGt0 > 1 : $time !== false; + return $shouldGt0 ? $shouldGt0 > 1 : $time !== false; } /** @@ -1228,24 +1226,24 @@ public static function date($val, $sholdGt0 = false): bool * * @return boolean */ - public static function dateEquals($val, $date): bool + public static function dateEquals(mixed $val, mixed $date): bool { if (!$val || (!$time = strtotime((string)$val))) { return false; } - return $date ? $time === strtotime((string)$date) : false; + return $date && $time === strtotime((string)$date); } /** * 校验字段值是否是日期并且是否满足设定格式 * - * @param string|mixed $val 日期 - * @param string $format 需要检验的格式数组 + * @param string|mixed $val 日期 + * @param string $format 需要检验的格式数组 * * @return bool */ - public static function dateFormat($val, string $format = 'Y-m-d'): bool + public static function dateFormat(mixed $val, string $format = 'Y-m-d'): bool { if (!$val || !($unixTime = strtotime($val))) { return false; @@ -1258,13 +1256,13 @@ public static function dateFormat($val, string $format = 'Y-m-d'): bool /** * 字段值必须是给定日期之前的值 * - * @param string|mixed $val + * @param string|mixed $val * @param string|numeric $beforeDate 若为空,将使用当前时间 - * @param string $symbol allow '<' '<=' + * @param string $symbol allow '<' '<=' * * @return bool */ - public static function beforeDate($val, $beforeDate = '', string $symbol = '<'): bool + public static function beforeDate(mixed $val, float|int|string $beforeDate = '', string $symbol = '<'): bool { if (!$val || !is_string($val)) { return false; @@ -1286,12 +1284,12 @@ public static function beforeDate($val, $beforeDate = '', string $symbol = '<'): /** * 字段值必须是小于或等于给定日期的值 * - * @param string|mixed $val + * @param string|mixed $val * @param string|numeric $beforeDate * * @return bool */ - public static function beforeOrEqualDate($val, $beforeDate): bool + public static function beforeOrEqualDate(mixed $val, float|int|string $beforeDate): bool { return self::beforeDate($val, $beforeDate, '<='); } @@ -1301,11 +1299,11 @@ public static function beforeOrEqualDate($val, $beforeDate): bool * * @param string|mixed $val * @param string|mixed $afterDate - * @param string $symbol allow: '>' '>=' + * @param string $symbol allow: '>' '>=' * * @return bool */ - public static function afterDate($val, $afterDate, string $symbol = '>'): bool + public static function afterDate(mixed $val, mixed $afterDate, string $symbol = '>'): bool { if (!$val || !is_string($val)) { return false; @@ -1332,7 +1330,7 @@ public static function afterDate($val, $afterDate, string $symbol = '>'): bool * * @return bool */ - public static function afterOrEqualDate($val, $afterDate): bool + public static function afterOrEqualDate(mixed $val, mixed $afterDate): bool { return self::afterDate($val, $afterDate, '>='); } @@ -1344,7 +1342,7 @@ public static function afterOrEqualDate($val, $afterDate): bool * * @return bool Validity is ok or not */ - public static function isDateFormat($date): bool + public static function isDateFormat(mixed $date): bool { if (!$date || !is_string($date)) { return false; @@ -1360,7 +1358,7 @@ public static function isDateFormat($date): bool * * @return bool Validity is ok or not */ - public static function isDate($date): bool + public static function isDate(mixed $date): bool { if (!$date || !is_string($date)) { return false; @@ -1382,7 +1380,7 @@ public static function isDate($date): bool * * @return bool */ - public static function phone($val): bool + public static function phone(mixed $val): bool { return 1 === preg_match('/^1[2-9]\d{9}$/', (string)$val); } @@ -1397,9 +1395,9 @@ public static function phone($val): bool * * @return bool Validity is ok or not */ - public static function postCode($val): bool + public static function postCode(mixed $val): bool { - return $val && is_string($val) && preg_match('/^\d{6}$/', (string)$val); + return $val && is_string($val) && preg_match('/^\d{6}$/', $val); } /** @@ -1409,7 +1407,7 @@ public static function postCode($val): bool * * @return bool Validity is ok or not */ - public static function price($price): bool + public static function price(mixed $price): bool { return 1 === preg_match('/^[\d]{1,10}(\.[\d]{1,9})?$/', (string)$price); } @@ -1421,7 +1419,7 @@ public static function price($price): bool * * @return bool Validity is ok or not */ - public static function negativePrice($price): bool + public static function negativePrice(mixed $price): bool { return 1 === preg_match('/^[-]?[\d]{1,10}(\.[\d]{1,9})?$/', (string)$price); } @@ -1433,7 +1431,7 @@ public static function negativePrice($price): bool * * @return bool Validity is ok or not */ - public static function isFloat($float): bool + public static function isFloat(mixed $float): bool { if (!is_scalar($float)) { return false; @@ -1447,7 +1445,7 @@ public static function isFloat($float): bool * * @return bool */ - public static function isUnsignedFloat($float): bool + public static function isUnsignedFloat(mixed $float): bool { if (!is_scalar($float)) { return false; @@ -1459,13 +1457,13 @@ public static function isUnsignedFloat($float): bool /** * Check for an integer validity * - * @param int $value Integer to validate + * @param int|float|string $value Integer to validate * * @return bool Validity is ok or not */ - public static function isInt($value): bool + public static function isInt(int|float|string $value): bool { - return ((string)(int)$value === (string)$value || $value === false); + return (string)(int)$value === (string)$value; } /** @@ -1475,7 +1473,7 @@ public static function isInt($value): bool * * @return bool Validity is ok or not */ - public static function isUnsignedInt($value): bool + public static function isUnsignedInt(float|int|string $value): bool { return ((string)(int)$value === (string)$value && $value < 4294967296 && $value >= 0); } @@ -1487,7 +1485,7 @@ public static function isUnsignedInt($value): bool * * @return bool Validity is ok or not */ - public static function md5($val): bool + public static function md5(mixed $val): bool { if (!$val || !is_string($val)) { return false; @@ -1503,7 +1501,7 @@ public static function md5($val): bool * * @return bool Validity is ok or not */ - public static function sha1($val): bool + public static function sha1(mixed $val): bool { if (!$val || !is_string($val)) { return false; @@ -1519,7 +1517,7 @@ public static function sha1($val): bool * * @return bool Validity is ok or not */ - public static function color($val): bool + public static function color(mixed $val): bool { if (!$val || !is_string($val)) { return false; @@ -1535,7 +1533,7 @@ public static function color($val): bool * * @return bool Validity is ok or not */ - public static function absoluteUrl($url): bool + public static function absoluteUrl(mixed $url): bool { if (!$url || !is_string($url)) { return false; @@ -1551,7 +1549,7 @@ public static function absoluteUrl($url): bool * * @return bool Validity is ok or not */ - public static function fileName($name): bool + public static function fileName(mixed $name): bool { if (!$name || !is_string($name)) { return false; @@ -1567,7 +1565,7 @@ public static function fileName($name): bool * * @return bool Validity is ok or not */ - public static function dirName($dir): bool + public static function dirName(mixed $dir): bool { if (!$dir || !is_string($dir)) { return false; diff --git a/test/Example/DataModel.php b/test/Example/DataModel.php index 49cd0df..4a6349c 100644 --- a/test/Example/DataModel.php +++ b/test/Example/DataModel.php @@ -11,23 +11,23 @@ class DataModel { use ValidationTrait; - protected $data = []; + protected array $data = []; - protected $db; + // protected $db; /** * @param array $data * * @return $this */ - public function setData($data): self + public function setData(array $data): self { $this->data = $data; return $this; } - public function create() + public function create(): bool|int { if ($this->validate()->isFail()) { return false; diff --git a/test/FieldValidationTest.php b/test/FieldValidationTest.php index 7018a29..a7e5cc1 100644 --- a/test/FieldValidationTest.php +++ b/test/FieldValidationTest.php @@ -15,7 +15,7 @@ */ class FieldValidationTest extends TestCase { - public $data = [ + public array $data = [ // 'userId' => 234, 'userId' => 'is not an integer', 'tagId' => '234535', diff --git a/test/Filter/FiltersTest.php b/test/Filter/FiltersTest.php index 7b228f3..7104d43 100644 --- a/test/Filter/FiltersTest.php +++ b/test/Filter/FiltersTest.php @@ -94,10 +94,10 @@ public function testStringFilter(): void $this->assertSame("O\'Reilly?", Filters::quotes("O'Reilly?")); // email - $this->assertSame('', Filters::email([])); + $this->assertSame('', Filters::email('')); // url - $this->assertSame('', Filters::url([])); + $this->assertSame('', Filters::url('')); $this->assertSame('abc/hi', Filters::url('abc/hi')); // unsafeRaw @@ -159,24 +159,20 @@ public function testChangeCase(): void // ucfirst $this->assertSame('Abc', Filters::ucfirst('abc')); $this->assertSame('', Filters::ucfirst('')); - $this->assertSame('', Filters::ucfirst([])); // ucwords $this->assertSame('Hello World', Filters::ucwords('hello world')); $this->assertSame('', Filters::ucwords('')); - $this->assertSame('', Filters::ucwords([])); // snake case $this->assertSame('hello_world', Filters::snake('HelloWorld')); $this->assertSame('hello-world', Filters::snake('HelloWorld', '-')); $this->assertSame('', Filters::snake('')); - $this->assertSame('', Filters::snake([])); // camel case $this->assertSame('helloWorld', Filters::camel('hello_world')); $this->assertSame('HelloWorld', Filters::camel('hello_world', true)); $this->assertSame('', Filters::camel('')); - $this->assertSame('', Filters::camel([])); } public function testTime(): void diff --git a/test/Filter/FiltrationTest.php b/test/Filter/FiltrationTest.php index 64b1fde..d1afca3 100644 --- a/test/Filter/FiltrationTest.php +++ b/test/Filter/FiltrationTest.php @@ -20,7 +20,7 @@ */ class FiltrationTest extends TestCase { - private $data = [ + private array $data = [ 'name' => ' tom ', 'status' => ' 23 ', 'word' => 'word', @@ -49,12 +49,12 @@ public function testUserFilters(): void $fl = Filtration::make($this->data); $fl->clearFilters(); $fl->addFilters([ - 'name1' => function () { + 'name1' => static function () { }, 'newTrim' => function ($val) { return trim($val); }, - '' => function () { + '' => static function () { }, ]); @@ -63,7 +63,7 @@ public function testUserFilters(): void $this->assertNotEmpty($fl->getFilter('newTrim')); $this->assertEmpty($fl->getFilter('name3')); - $fl->addFilter('new1', function () { + $fl->addFilter('new1', static function () { }); $this->assertNotEmpty($fl->getFilter('new1')); diff --git a/test/Filter/UserFiltersTest.php b/test/Filter/UserFiltersTest.php index d6d0680..fdee052 100644 --- a/test/Filter/UserFiltersTest.php +++ b/test/Filter/UserFiltersTest.php @@ -22,11 +22,11 @@ public function testBasic(): void { UserFilters::removeAll(); UserFilters::setFilters([ - 'name1' => function () { + 'name1' => static function () { }, - 'name2' => function () { + 'name2' => static function () { }, - '' => function () { + '' => static function () { }, ]); @@ -37,7 +37,7 @@ public function testBasic(): void $this->assertNotEmpty(UserFilters::get('name2')); $this->assertEmpty(UserFilters::get('name3')); - UserFilters::add('new1', function () { + UserFilters::add('new1', static function () { }); $this->assertTrue(UserFilters::has('new1')); diff --git a/test/HelperTest.php b/test/HelperTest.php index 740d250..6d88c58 100644 --- a/test/HelperTest.php +++ b/test/HelperTest.php @@ -50,7 +50,7 @@ public function testCompareSize(): void { $this->assertTrue(Helper::compareSize(5, '>', 3)); - $this->assertFalse(Helper::compareSize(true, '>', false)); + // $this->assertFalse(Helper::compareSize(true, '>', false)); $this->assertFalse(Helper::compareSize(5, 'invalid', 3)); } @@ -86,7 +86,7 @@ public function testCall(): void $this->assertSame(34, Helper::call(Filters::class . '::integer', '34')); $callabled = new class { - public function __invoke($str) + public function __invoke($str): int { return (int)$str; } diff --git a/test/RuleValidationTest.php b/test/RuleValidationTest.php index 528f176..8f981dc 100644 --- a/test/RuleValidationTest.php +++ b/test/RuleValidationTest.php @@ -244,7 +244,7 @@ public function testCollectRules(): void $this->assertCount(4, $v->getUsedRules()); } - public $data = [ + public array $data = [ // 'userId' => 234, 'userId' => 'is not an integer', 'tagId' => '35', diff --git a/test/Simple/ValidDataTest.php b/test/Simple/ValidDataTest.php index e0a2d6b..cd8a9ae 100644 --- a/test/Simple/ValidDataTest.php +++ b/test/Simple/ValidDataTest.php @@ -12,7 +12,7 @@ */ class ValidDataTest extends BaseValidateTestCase { - public $testData = [ + public array $testData = [ 'int' => 23, 'num' => '23', 'str' => 'abc', diff --git a/test/Traits/ErrorMessageTraitTest.php b/test/Traits/ErrorMessageTraitTest.php index c29171a..99e0f04 100644 --- a/test/Traits/ErrorMessageTraitTest.php +++ b/test/Traits/ErrorMessageTraitTest.php @@ -11,7 +11,7 @@ */ class ErrorMessageTraitTest extends TestCase { - private $sampleDate = [ + private array $sampleDate = [ // 'userId' => 234, 'userId' => 'is not an integer', 'tagId' => '234535', diff --git a/test/Traits/ScopedValidatorsTest.php b/test/Traits/ScopedValidatorsTest.php index 66f5faf..4efadb5 100644 --- a/test/Traits/ScopedValidatorsTest.php +++ b/test/Traits/ScopedValidatorsTest.php @@ -25,11 +25,11 @@ public function testUserValidators(): void $v = Validation::make([]); $v->clearValidators(); $v->addValidators([ - 'name1' => function () { + 'name1' => static function () { }, - 'name2' => function () { + 'name2' => static function () { }, - '' => function () { + '' => static function () { }, ]); @@ -40,7 +40,7 @@ public function testUserValidators(): void $this->assertNotEmpty($v->getValidator('name2')); $this->assertEmpty($v->getValidator('name3')); - $v->addValidator('name4', function () { + $v->addValidator('name4', static function () { }); $this->assertNotEmpty($v->getValidator('name4')); diff --git a/test/ValidationTraitTest.php b/test/ValidationTraitTest.php index 2ba6efe..f8d3681 100644 --- a/test/ValidationTraitTest.php +++ b/test/ValidationTraitTest.php @@ -90,7 +90,7 @@ public function testGetByPath(): void /** * @var \array[][] see PR https://github.com/inhere/php-validate/pull/19 */ - public $deepData = [ + public array $deepData = [ 'companies' => [ [ 'name' => 'ms', diff --git a/test/Validator/AdemoValidatorTest.php b/test/Validator/AdemoValidatorTest.php index 1e31c5f..536b322 100644 --- a/test/Validator/AdemoValidatorTest.php +++ b/test/Validator/AdemoValidatorTest.php @@ -17,7 +17,7 @@ class AdemoValidatorTest extends AbstractValidator * * @return bool */ - public function validate($value, array $data): bool + public function validate(mixed $value, array $data): bool { return $value === 1; } diff --git a/test/Validator/Rule.php b/test/Validator/Rule.php index 6f7ce39..c8c9e02 100644 --- a/test/Validator/Rule.php +++ b/test/Validator/Rule.php @@ -21,7 +21,7 @@ final class Rule /** * @var string */ - public $field; + public string $field; /** * validator name OR validator object @@ -33,29 +33,29 @@ final class Rule /** * @var array */ - public $params = []; + public array $params = []; /** * @var Closure */ - public $when; + public Closure $when; /** * @var mixed */ - public $value; + public mixed $value; /** * @var mixed */ - public $default; + public mixed $default; /** * default error message * * @var mixed */ - public $message; + public mixed $message; /** * check Empty @@ -67,12 +67,12 @@ final class Rule /** * @var bool */ - public $skipOnEmpty = true; + public bool $skipOnEmpty = true; /** * @var array|null */ - public $filters; + public ?array $filters; public static function createByArray(array $config): void { @@ -81,14 +81,14 @@ public static function createByArray(array $config): void /** * @param string $field 属性名称 * @param mixed $value 属性值 - * @param Closure|string $validator 验证器 + * @param string|Closure $validator 验证器 * @param array $params 验证需要的参数 - * @param string $message default error message + * @param string $message default error message * @param mixed $default default value * * @return Rule */ - public function init(string $field, $value, $validator, array $params, $message, $default): Rule + public function init(string $field, mixed $value, string|Closure $validator, array $params, string $message, mixed $default): Rule { $this->field = $field; $this->value = $value; diff --git a/test/Validator/UserValidatorsTest.php b/test/Validator/UserValidatorsTest.php index 5d45ed6..4f39ae7 100644 --- a/test/Validator/UserValidatorsTest.php +++ b/test/Validator/UserValidatorsTest.php @@ -22,11 +22,11 @@ public function testBasic(): void { UserValidators::removeAll(); UserValidators::setValidators([ - 'name1' => function () { + 'name1' => static function () { }, - 'name2' => function () { + 'name2' => static function () { }, - '' => function () { + '' => static function () { }, ]); diff --git a/test/ValidatorsTest.php b/test/ValidatorsTest.php index f36bdf2..ab04c54 100644 --- a/test/ValidatorsTest.php +++ b/test/ValidatorsTest.php @@ -152,7 +152,7 @@ public function testAlphaNum(): void public function testAlphaDash(): void { $this->assertFalse(Validators::alphaDash('=')); - $this->assertFalse(Validators::alphaDash(null)); + // $this->assertFalse(Validators::alphaDash(null)); $this->assertFalse(Validators::alphaDash('test=')); $this->assertTrue(Validators::alphaDash('sdf56-_')); @@ -242,8 +242,8 @@ public function testValueCompare(): void public function testSize(): void { $this->assertFalse(Validators::size('test', 5)); - $this->assertFalse(Validators::size(null, 5)); - $this->assertFalse(Validators::range(new stdClass(), 5)); + // $this->assertFalse(Validators::size(null, 5)); + $this->assertFalse(Validators::range('test', 5)); $this->assertFalse(Validators::between(56, 20, 50)); $this->assertTrue(Validators::size(56, 20, 100)); @@ -268,7 +268,7 @@ public function testLength(): void { $this->assertFalse(Validators::length('test', 5)); $this->assertFalse(Validators::length('test', 0, 3)); - $this->assertFalse(Validators::length(56, 60)); + // $this->assertFalse(Validators::length(56, 60)); $this->assertTrue(Validators::length('test', 3, 5)); $this->assertTrue(Validators::length([3, 'test', 'hi'], 2, 5)); @@ -415,7 +415,7 @@ public function testArrList(): void public function testHasKey(): void { $this->assertFalse(Validators::hasKey('hello, world', 'all')); - $this->assertFalse(Validators::hasKey('hello, world', true)); + $this->assertFalse(Validators::hasKey('hello, world', 'not')); $this->assertFalse(Validators::hasKey(['a' => 'v0', 'b' => 'v1', 'c' => 'v2'], 'd')); $this->assertFalse(Validators::hasKey(['a' => 'v0', 'b' => 'v1', 'c' => 'v2'], ['c', 'd'])); @@ -471,7 +471,7 @@ public function testContains(): void $this->assertFalse(Validators::contains('hello, world', 'all')); $this->assertFalse(Validators::contains(null, 'all')); $this->assertFalse(Validators::contains([], 'all')); - $this->assertFalse(Validators::contains('hello, world', false)); + // $this->assertFalse(Validators::contains('hello, world', false)); $this->assertTrue(Validators::contains('123', 2)); $this->assertTrue(Validators::contains('hello, world', 'llo')); diff --git a/test/bootstrap.php b/test/bootstrap.php index a91c0d7..b391d9f 100644 --- a/test/bootstrap.php +++ b/test/bootstrap.php @@ -14,7 +14,7 @@ 'Inhere\\ValidateTest\\' => $libDir . '/test/', ]; -spl_autoload_register(function ($class) use ($npMap) { +spl_autoload_register(static function ($class) use ($npMap) { foreach ($npMap as $np => $dir) { $file = $dir . str_replace('\\', '/', substr($class, strlen($np))) . '.php';