### Install Weimeng Validate Middleware (Composer) Source: https://v.itwmw.com/plugin/Middleware This snippet shows the Composer command to install the Weimeng validation middleware package. This is a prerequisite for using the middleware in your project. ```bash composer require itwmw/validate-middleware ``` -------------------------------- ### Install Micro Dream Form Validate using Composer Source: https://v.itwmw.com/en/6/Guide This command installs the Micro Dream Form Validate extension using Composer, a dependency manager for PHP. Ensure Composer is installed on your system. ```bash composer require itwmw/validate ``` -------------------------------- ### Size Validation Examples (PHP) Source: https://v.itwmw.com/6/BuiltRule Demonstrates how to use the 'size' validation rule for strings, numbers, arrays, and files in PHP. It shows how to specify exact sizes and compare with other fields. ```php 'title' => 'size:12'; ``` ```php 'seats' => 'integer|size:10'; ``` ```php 'tags' => 'array|size:5'; ``` ```php 'image' => 'file|size:512'; ``` -------------------------------- ### Define Processor with Constructor Parameters Source: https://v.itwmw.com/6/Processor Illustrates creating a processor class that accepts parameters via its constructor. This allows for more flexible processing, such as specifying allowed HTML tags. The example shows how to pass a comma-separated string of tags to the constructor. ```php class RemoveScriptProcessor implements ProcessorInterface { protected array $allowTags; public function __construct(string $allowTags = '') { $this->allowTags = explode(',', $allowTags); } public function handle($value, string $attribute, array $originalData) { // 处理script demo,仅供展示 $value = preg_replace('/.*?/si', '', $value); return strip_tags($value, $this->allowTags); } } ``` -------------------------------- ### Skip Elements from Start with skip() in PHP Source: https://v.itwmw.com/6/Collection The `skip` method returns a new collection containing all elements except for the specified number of elements from the beginning. The original collection remains unchanged. ```php $collection = validate_collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $collection = $collection->skip(4); $collection->all(); // [5, 6, 7, 8, 9, 10] ``` -------------------------------- ### Retrieve Value by Key with get() Source: https://v.itwmw.com/5/Collection The get method retrieves the value associated with a given key. If the key does not exist, it returns null by default, but a default value or a callback function can be provided as a fallback. It also supports nested key retrieval using dot notation and wildcard matching. ```php $collection = validate_collect(['name' => 'yuyu', 'age' => '88']); $value = $collection->get('name'); // yuyu $value = $collection->get('sex', 1); // 1 $collection->get('email', function () { return 'yuyu@example.com'; }); // yuyu@example.com $collection = validate_collect([ 'info' => [ 'name' => 'yuyu', 'age' => '88' ] ]); $collection->get('info.name'); // yuyu $collection = validate_collect([ 'info' => [ [ 'name' => 'yuyu', 'age' => '88' ], [ 'name' => 'haha', 'age' => '60' ] ] ]); $collection->get('info.*.name'); /* Array ( [0] => yuyu [1] => haha ) */ ``` -------------------------------- ### keys: Get All Collection Keys (PHP) Source: https://v.itwmw.com/6/Collection The `keys` method returns all of the keys present in the collection. This is useful for retrieving the identifiers of the collection's items. ```php $collection = validate_collect([ 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'], 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'], ]); $keys = $collection->keys(); $keys->all(); // ['prod-100', 'prod-200'] ``` -------------------------------- ### Get Validation Data in PHP Source: https://v.itwmw.com/5/Scene Retrieves the current validated data. By default, it fetches all validated values. An optional key can be provided to get a specific value, with a default fallback. ```php public function getData(string $key = '', $default = null) ``` -------------------------------- ### Specify Next Scene in PHP Source: https://v.itwmw.com/5/Scene Specifies the name of the next scene or a scene selector to be processed. Refer to usage examples for scene reuse and association. ```php public function next(string $name): static ``` -------------------------------- ### Get All Collection Keys with keys (PHP) Source: https://v.itwmw.com/5/Collection The keys method returns all of the keys for the given collection. This is useful for iterating over or inspecting the structure of a collection. Dependencies: IlluminateSupportCollection. ```php $collection = validate_collect([ 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'], 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'], ]); $keys = $collection->keys(); $keys->all(); // ['prod-100', 'prod-200'] ``` -------------------------------- ### Extend Collection with Macro Source: https://v.itwmw.com/en/6/Collection Illustrates how to add custom methods to the `Collection` class using the `macro` method. This example adds a `toUpper` method that converts all string elements in the collection to uppercase. ```php use Itwmw\Validation\Support\Collection\Collection; use Illuminate\Support\Str; Collection::macro('toUpper', function () { return $this->map(function ($value) { return Str::upper($value); }); }); $collection = validate_collect(['first', 'second']); $upper = $collection->toUpper(); // ['FIRST', 'SECOND'] ``` -------------------------------- ### Passing Parameters to Processors (PHP) Source: https://v.itwmw.com/en/6/Processor Shows how to pass parameters directly to processors, in addition to using `ProcessorParams`. This example uses `explode` with a comma delimiter and then `array_map` to convert string numbers to integers. ```php class Test extends Validate { protected $rule = [ 'id' => 'required|string' ]; protected $postprocessor = [ 'id' => [ ProcessorOptions::MULTIPLE, ['explode', ',', ProcessorParams::Value], ['array_map', 'intval', ProcessorParams::Value], ], ]; } $data = Test::make()->check([ 'id' => '1,2,3,4,5' ]); var_dump($data); ``` -------------------------------- ### Get First Element with first() in PHP Source: https://v.itwmw.com/6/Collection The first method returns the first element in a collection that passes a test defined by a callback function. If no callback is provided, it returns the very first element of the collection. Returns null if the collection is empty. ```php validate_collect([1, 2, 3, 4])->first(function ($value, $key) { return $value > 2; }); // 3 ``` ```php validate_collect([1, 2, 3, 4])->first(); // 1 ``` -------------------------------- ### Get Slice of Collection by Offset using slice() Source: https://v.itwmw.com/5/Collection The `slice` method returns a new collection containing a portion of the original collection, starting from a given index. An optional length parameter can limit the number of items returned. Original keys are preserved unless `values()` is used. ```php $collection = validate_collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $slice = $collection->slice(4); $slice->all(); // [5, 6, 7, 8, 9, 10] ``` ```php $slice = $collection->slice(4, 2); $slice->all(); // [5, 6] ``` -------------------------------- ### PHP: 使用实现了ProcessorInterface的类作为处理器 Source: https://v.itwmw.com/5/Processor 创建一个实现了 `ProcessorInterface` 接口的类,并在 `$preprocessor` 或 `$postprocessor` 属性中直接引用该类的类名。处理器类需要实现 `handle` 方法。 ```php use Itwmw\Validate\Support\Concerns\ProcessorInterface; use Itwmw\Validate\Validate; class RemoveScriptProcessor implements ProcessorInterface { public function handle($value, string $attribute, array $originalData) { // 处理script demo,仅供展示 $value = preg_replace('/.*?/si', '', $value); return strip_tags($value); } } class Test extends Validate { protected $rule = [ 'name' => 'nullable|string', ]; protected $postprocessor = [ 'name' => RemoveScriptProcessor::class, ]; } $data = Test::make()->check([ 'name' => '名称' ]); var_dump($data); //array(1) { // ["name"]=> // string(6) "名称" //} ``` -------------------------------- ### PHP: 使用类属性定义多个处理器 Source: https://v.itwmw.com/5/Processor 通过在 `$preprocessor` 或 `$postprocessor` 属性中设置 `ProcessorOptions::MULTIPLE` 来为同一字段定义多个处理器。这些处理器将按顺序依次执行。 ```php use Itwmw\Validate\Support\Processor\ProcessorExecCond; use Itwmw\Validate\Support\Processor\ProcessorOptions; use Itwmw\Validate\Support\Processor\ProcessorParams; use Itwmw\Validate\Validate; class Test extends Validate { protected $rule = [ 'name' => 'nullable|string', ]; protected $preprocessor = [ 'name' => [ ProcessorOptions::MULTIPLE, ['默认名称', ProcessorExecCond::WHEN_EMPTY], ['trim', ProcessorParams::Value], ] ]; } ``` -------------------------------- ### Processor Class with Constructor Parameters Source: https://v.itwmw.com/en/6/Processor This example illustrates how a processor class, `RemoveScriptProcessor`, can accept parameters via its constructor. The constructor takes an `allowTags` string, which is used to configure the `strip_tags` function within the `handle` method. This allows for customizable filtering of HTML tags. ```php class RemoveScriptProcessor implements ProcessorInterface { protected array $allowTags; public function __construct(string $allowTags = '') { $this->allowTags = explode(',', $allowTags); } public function handle($value, string $attribute, array $originalData) { // This is a demo for remove scripts, for display purposes only $value = preg_replace('/.*?/si', '', $value); return strip_tags($value, $this->allowTags); } } ``` -------------------------------- ### PHP: 使用类属性定义前置和后置处理器 Source: https://v.itwmw.com/5/Processor 通过 `$preprocessor` 和 `$postprocessor` 属性为验证器定义前置和后置数据处理器。前置处理器在验证前执行,后置处理器在验证后执行。可以指定执行条件和参数。 ```php use Itwmw\Validate\Support\Processor\ProcessorExecCond; use Itwmw\Validate\Support\Processor\ProcessorOptions; use Itwmw\Validate\Support\Processor\ProcessorParams; use Itwmw\Validate\Validate; class Test extends Validate { protected $rule = [ 'name' => 'nullable|string', ]; protected $preprocessor = [ 'name' => ['默认名称', ProcessorExecCond::WHEN_EMPTY] ]; protected $postprocessor = [ 'name' => ['trim', ProcessorParams::Value] ]; } ``` -------------------------------- ### Define Multiple Processors in Class Properties (PHP) Source: https://v.itwmw.com/en/5/Processor This example shows how to configure multiple preprocessors and postprocessors for a single field using ProcessorOptions::MULTIPLE. It first applies a default value if the field is empty, then trims the value. ```php use Itwmw\Validate\Support\Processor\ProcessorExecCond; use Itwmw\Validate\Support\Processor\ProcessorOptions; use Itwmw\Validate\Support\Processor\ProcessorParams; use Itwmw\Validate\Validate; class Test extends Validate { protected $rule = [ 'name' => 'nullable|string', ]; protected $preprocessor = [ 'name' => [ ProcessorOptions::MULTIPLE, ['Default Name', ProcessorExecCond::WHEN_EMPTY], ['trim', ProcessorParams::Value], ] ]; } ``` -------------------------------- ### PHP: 在验证场景中定义处理器 Source: https://v.itwmw.com/5/Processor 可以在验证场景类中通过 `preprocessor()` 和 `postprocessor()` 方法来定义数据处理器。这允许为不同的验证场景配置不同的数据处理逻辑。 ```php use Itwmw\Validate\Support\Processor\ProcessorExecCond; use Itwmw\Validate\Support\Processor\ProcessorParams; use Itwmw\Validate\Validate; use Itwmw\Validate\ValidateScene; class Test extends Validate { protected $rule = [ 'name' => 'nullable|string', ]; protected function sceneSave(ValidateScene $scene): void { $scene->only(true) ->preprocessor('name', '默认名称', ProcessorExecCond::WHEN_EMPTY) ->postprocessor('name', 'trim', ProcessorParams::Value); } } $data = Test::make()->scene('save')->check([]); var_dump($data); //array(1) { // ["name"]=> // string(12) "默认名称" //} $data = Test::make()->check([]); var_dump($data); //array(0) { //} ``` -------------------------------- ### Get item from collection by key or path in PHP Source: https://v.itwmw.com/en/6/Collection The get method retrieves an item from a collection using a key, dot notation for nested keys, or wildcard notation for arrays. It returns null if the key doesn't exist, but can also accept a default value or a callback for a default. This method is versatile for accessing data. ```php $collection = validate_collect(['name' => 'yuyu', 'framework' => 'laravel']); $value = $collection->get('name'); // yuyu ``` ```php $collection = validate_collect(['name' => 'yuyu', 'framework' => 'laravel']); $value = $collection->get('age', 34); // 34 ``` ```php $collection->get('email', function () { return 'yuyu@example.com'; }); // yuyu@example.com ``` ```php $collection = validate_collect([ 'info' => [ 'name' => 'yuyu', 'age' => '88' ] ]); $collection->get('info.name'); // yuyu ``` ```php $collection = validate_collect([ 'info' => [ [ 'name' => 'yuyu', 'age' => '88' ], [ 'name' => 'haha', 'age' => '60' ] ] ]); $collection->get('info.*.name'); /* Array ( [0] => yuyu [1] => haha ) */ ``` -------------------------------- ### Define Validation Rules and Scenarios (PHP) Source: https://v.itwmw.com/en/5/Scene This snippet demonstrates how to define validation rules for fields and how to group them into specific validation scenarios using the $rule and $scene properties. It's a fundamental setup for validation logic. ```php protected $rule = [ 'search.order' => 'numeric|between:1,2', 'search.keyword' => 'chsAlphaNum', 'search.recycle' => 'boolean', ]; protected $scene = [ 'list' => ['search.order','search.keyword','search.recycle'] ]; ``` -------------------------------- ### 实现数据处理器接口 Source: https://v.itwmw.com/5/Log 定义一个数据处理器类,需要实现 `Itwmw\Validate\Support\Concerns\ProcessorInterface` 接口。该接口用于在验证前后处理数据,一个字段可使用多个处理器。 ```php 'nullable|string', ]; protected function sceneSave(ValidateScene $scene): void { $scene->only(true) ->preprocessor('name', function (mixed $value, string $attribute, array $data) { if (empty($value)) { return '默认名称'; } return $value; }, ProcessorParams::Value, ProcessorParams::Attribute, ProcessorParams::OriginalData); } } $data = Test::make()->scene('save')->check([]); var_dump($data); //array(1) { // ["name"]=> // string(12) "默认名称" //} ``` -------------------------------- ### Get strictly unique items from collection with uniqueStrict() in PHP Source: https://v.itwmw.com/en/5/Collection The `uniqueStrict` method is similar to `unique` but uses strict comparisons to determine uniqueness. ```php // Assumes $collection is already defined and populated // Example usage: // $collection = validate_collect([1, '1', 2, 2]); // $uniqueStrict = $collection->uniqueStrict(); // $uniqueStrict->values()->all(); // [1, 2] ``` -------------------------------- ### Filter Collection by Price Range (whereBetween) Source: https://v.itwmw.com/6/Collection The `whereBetween` method filters a collection to include items where the specified key's value falls within a given range (inclusive). It takes the key and an array of two values representing the start and end of the range. ```php $collection = validate_collect([ ['product' => 'Desk', 'price' => 200], ['product' => 'Chair', 'price' => 80], ['product' => 'Bookcase', 'price' => 150], ['product' => 'Pencil', 'price' => 30], ['product' => 'Door', 'price' => 100], ]); $filtered = $collection->whereBetween('price', [100, 200]); $filtered->all(); /* [ ['product' => 'Desk', 'price' => 200], ['product' => 'Bookcase', 'price' => 150], ['product' => 'Door', 'price' => 100], ] */ ``` -------------------------------- ### Define and Use a Basic Processor Source: https://v.itwmw.com/6/Processor Demonstrates how to define a simple processor class that implements ProcessorInterface and how to apply it to a validation rule. The processor removes script tags and applies strip_tags. It has no constructor parameters. ```php class RemoveScriptProcessor implements ProcessorInterface { public function handle($value, string $attribute, array $originalData) { // 处理script demo,仅供展示 $value = preg_replace('/.*?/si', '', $value); return strip_tags($value); } } class Test extends Validate { protected $rule = [ 'name' => 'nullable|string', ]; protected $postprocessor = [ 'name' => RemoveScriptProcessor::class, ]; } $data = Test::make()->check([ 'name' => '名称' ]); var_dump($data); //array(1) { // ["name"]=> // string(6) "名称" //} ``` -------------------------------- ### PHP Built-in Type Casting: String Source: https://v.itwmw.com/en/6/Casts Example of casting a value to a string using the 'string' type in the `$casts` property. ```PHP protected $casts = ['zipcode' => 'string']; // 12345 -> '12345' ``` -------------------------------- ### Implementing Processor Interface for Custom Processors in Itwmw Validate Source: https://v.itwmw.com/en/5/Processor Details how to create reusable processor logic by implementing the `ProcessorInterface`. This allows for separation of concerns and promotes code reusability. The example defines a `RemoveScriptProcessor` to clean HTML input by removing script tags and stripping other tags. ```php class RemoveScriptProcessor implements \Itwmw\Validate\Support\Concerns\ProcessorInterface { public function handle($value, string $attribute, array $originalData) { // This is a demo for remove scripts, for display purposes only $value = preg_replace('/.*?/si', '', $value); return strip_tags($value); } } class Test extends \Itwmw\Validate\Validate { protected $rule = [ 'name' => 'nullable|string', ]; protected $postprocessor = [ 'name' => RemoveScriptProcessor::class, ]; } $data = Test::make()->check([ 'name' => 'Name' ]); var_dump($data); //array(1) { // ["name"]=> // string(6) "Name" //} ``` -------------------------------- ### PHP Built-in Type Casting: Float Source: https://v.itwmw.com/en/6/Casts Example of casting a value to a float using the 'float' type in the `$casts` property. ```PHP protected $casts = ['price' => 'float']; // '19.99' -> 19.99 ``` -------------------------------- ### PHP Built-in Type Casting: Integer Source: https://v.itwmw.com/en/6/Casts Example of casting a value to an integer using the 'int' type in the `$casts` property. ```PHP protected $casts = ['age' => 'int']; // '30' -> 30 ``` -------------------------------- ### 实现存在验证器接口 - PHP Source: https://v.itwmw.com/5/Start 当使用 `Exists` 和 `Unique` 验证规则时,需要实现 `PresenceVerifierInterface` 接口。此接口定义了与数据库交互以验证数据存在性的方法。配置此验证器后,即可使用需要数据库操作的验证规则。 ```php namespace App\Validation\Presence; use Itwmw\Validation\Support\Interfaces\PresenceVerifierInterface; use Itwmw\Validation\Support\ValidateConfig; class PresenceVerifier implements PresenceVerifierInterface { // 实现 PresenceVerifierInterface 的方法 } // 配置存在验证器 ValidateConfig::instance()->setPresenceVerifier(new PresenceVerifier()); ``` -------------------------------- ### 在验证场景中使用数据处理器 (PHP) Source: https://v.itwmw.com/6/Processor 通过 `ValidateScene` 类的方法(如 `preprocessor`, `postprocessor`)在验证场景中定义数据处理器,实现场景特定的数据处理逻辑。 ```php use Itwmw\Validate\Support\ValidateScene; use Itwmw\Validate\Support\Processor\ProcessorExecCond; use Itwmw\Validate\Support\Processor\ProcessorParams; use Itwmw\Validate\Validate; class Test extends Validate { protected $rule = [ 'name' => 'nullable|string', ]; protected function sceneSave(ValidateScene $scene): void { $scene->only(true) ->preprocessor('name', '默认名称', ProcessorExecCond::WHEN_EMPTY) ->postprocessor('name', 'trim', ProcessorParams::Value); } } $data = Test::make()->scene('save')->check([]); var_dump($data); $data = Test::make()->check([]); var_dump($data); ``` -------------------------------- ### 独立调用自定义规则对象 Source: https://v.itwmw.com/5/Rule 可以直接实例化并调用自定义规则对象的方法来执行验证逻辑,无需通过验证器。这适用于单独测试或在非验证器场景下使用规则。 ```php Chs::make()->check("名字"); ``` -------------------------------- ### Get strictly unique items from a collection (PHP) Source: https://v.itwmw.com/5/Collection The `uniqueStrict` method functions like `unique`, but it performs strict type and value comparisons when determining uniqueness. ```php $collection = validate_collect([1, '1', 2, '2', 3]); $uniqueStrict = $collection->uniqueStrict(); $uniqueStrict->values()->all(); // [1, "1", 2, "2", 3] ``` -------------------------------- ### PHP - 使用 event 方法添加场景事件 Source: https://v.itwmw.com/6/Event 展示了如何在自定义验证场景中使用 `$scene->event()` 方法来动态添加场景事件处理器。可以不传参数,也可以传递参数给事件处理器。支持链式调用添加多个事件处理器。 ```php /* * @method $this event(string $handler,...$params) */ $scene->event(CheckPermission::class) $scene->event(CheckPermission::class,1,2,3)->event(CheckName::class) ``` -------------------------------- ### 使用闭包作为数据处理器 (PHP) Source: https://v.itwmw.com/6/Processor 在验证场景中,可以直接传递闭包函数作为处理器。闭包可以接收 `value`, `attribute`, `data` 等参数,实现自定义逻辑。 ```php use Itwmw\Validate\Support\ValidateScene; use Itwmw\Validate\Support\Processor\ProcessorParams; use Itwmw\Validate\Validate; class Test extends Validate { protected $rule = [ 'name' => 'nullable|string', ]; protected function sceneSave(ValidateScene $scene): void { $scene->only(true) ->preprocessor('name', function (mixed $value, string $attribute, array $data) { if (empty($value)) { return '默认名称'; } return $value; }, ProcessorParams::Value, ProcessorParams::Attribute, ProcessorParams::OriginalData); } } $data = Test::make()->scene('save')->check([]); var_dump($data); ``` -------------------------------- ### Get Validation Data Collection in PHP Source: https://v.itwmw.com/5/Scene Retrieves the current validated data, similar to `getData()`. The key difference is that this method returns a `ValidateCollection` class instance. ```php public function getValidateData(): ValidateCollection ``` -------------------------------- ### 配置自定义规则路径 (Symfony) Source: https://v.itwmw.com/6/Start 为了让微梦表单验证器能够自动发现和加载自定义的验证规则类,需要配置自定义规则类的命名空间前缀。这使得验证器能够根据提供的路径前缀查找并使用用户定义的规则。 ```php use Itwmw\Validation\ValidationConfig; // 假设自定义规则的完整命名空间是 Itwmw\App\Model\Validate\Rules\MyCustomRule // 则配置前缀为 Itwmw\App\Model\Validate\Rules\ ValidateConfig::instance()->setRulesPath('Itwmw\App\Model\Validate\Rules\'); ``` -------------------------------- ### PHP Built-in Type Casting: Array Source: https://v.itwmw.com/en/6/Casts Example of casting a JSON string to a PHP array using the 'array' type in the `$casts` property. ```PHP protected $casts = ['options' => 'array']; // '{"color":"red"}' -> ['color' => 'red'] ``` -------------------------------- ### 配置自定义规则类路径 - PHP Source: https://v.itwmw.com/5/Start 为了让验证器能够自动发现自定义的验证规则类,需要配置自定义规则的命名空间前缀。这使得验证器能够根据命名空间找到并加载用户定义的规则。 ```php use Itwmw\Validation\Support\ValidateConfig; // 假设自定义规则的完整命名空间为:Itwmw\App\Model\Validate\Rules\AlphaDash ValidateConfig::instance()->setRulesPath('Itwmw\App\Model\Validate\Rules\'); ``` -------------------------------- ### PHP: 使用类方法定义处理器 Source: https://v.itwmw.com/5/Processor 在当前验证器类中定义一个方法,并遵循 `方法名 + Processor` 的命名规则(例如 `setDefaultNameProcessor`),该方法即可被用作数据处理器。 ```php use Itwmw\Validate\Validate; class Test extends Validate { protected $rule = [ 'name' => 'nullable|string', ]; protected $preprocessor = [ 'name' => 'setDefaultName', ]; protected function setDefaultNameProcessor(mixed $value) { return empty($value) ? '默认名称' : $value; } } $data = Test::make()->check([]); var_dump($data); //array(1) { // ["name"]=> // string(12) "默认名称" //} ``` -------------------------------- ### Configure Custom Rule Class Paths Source: https://v.itwmw.com/en/5/Start This code example illustrates how to configure custom rule class paths for the validator. By setting the correct namespace prefix, the validator can automatically discover and utilize custom validation rule classes, simplifying the process of adding new validation logic. ```php ValidateConfig::instance()->setRulesPath('Itwmw\App\Model\Validate\Rules\'); ``` -------------------------------- ### PHP Enum Class Casting: Pure Enum Source: https://v.itwmw.com/en/6/Casts Example of casting a value to a pure PHP enumeration using its class name in the `$casts` property. ```PHP // enum LoginFrom { case PC; ... } protected $casts = ['login_from' => LoginFrom::class]; // 'PC' -> LoginFrom::PC ``` -------------------------------- ### 动态设置验证场景 Source: https://v.itwmw.com/5/Validate 演示如何使用`setScene`方法动态设置或追加验证场景,并可以传入`null`来清空所有验证场景。 ```php // 类中定义 protected $scene = [ 'login' => ['user', 'pass'] ]; // 使用方法定义 $v->setScene([ 'login' => ['user', 'pass'] ]); ``` -------------------------------- ### PHP Enum Class Casting: Backed Enum Source: https://v.itwmw.com/en/6/Casts Example of casting a value to a backed PHP enumeration using its class name in the `$casts` property. ```PHP // enum ProductType: int { case BOOK = 1; ... } protected $casts = ['product_type' => ProductType::class]; // 1 -> ProductType::BOOK // 'BOOK' -> ProductType::BOOK ``` -------------------------------- ### 使用extend方法注册静态类方法规则 Source: https://v.itwmw.com/5/Rule 对于静态方法,可以将包含完整类名的数组和方法名传递给`extend`方法来注册自定义验证规则。这允许使用静态方法实现验证逻辑,无需实例化类。 ```php class Rules { public static function chs($attribute, $value, $parameters, $validator) { return is_scalar($value) && 1 === preg_match('/^[x{4e00}-x{9fa5}]+$/u', (string)$value); } } $v->extend('chs', [Rules::class, 'chs'], ':attribute的值只能具有中文'); ``` -------------------------------- ### PHP Built-in Type Casting: Collection Source: https://v.itwmw.com/en/6/Casts Example of casting an array or JSON string to an Itwmw\Validation\Support\Collection\Collection object using the 'collection' type in the `$casts` property. ```PHP protected $casts = ['users' => 'collection']; ``` -------------------------------- ### 使用类方法作为数据处理器 (PHP) Source: https://v.itwmw.com/6/Processor 可以在当前类中定义一个方法(命名规则:首字母小写的方法名 + `Processor`),并将其作为处理器名使用,实现类内部的方法调用。 ```php use Itwmw\Validate\Validate; class Test extends Validate { protected $rule = [ 'name' => 'nullable|string', ]; protected $preprocessor = [ 'name' => 'setDefaultName', ]; protected function setDefaultNameProcessor(mixed $value) { return empty($value) ? '默认名称' : $value; } } $data = Test::make()->check([]); var_dump($data); ``` -------------------------------- ### PHP Built-in Type Casting: JSON Source: https://v.itwmw.com/en/6/Casts Example of casting a PHP array or object to a JSON string using the 'json' type in the `$casts` property. ```PHP protected $casts = ['properties' => 'json']; // ['color' => 'red'] -> '{"color":"red"}' ``` -------------------------------- ### Define Data Processor using Class Method Source: https://v.itwmw.com/en/6/Processor This example shows how to define a data preprocessor by specifying a method name within the current class. The method `setDefaultNameProcessor` handles the logic, returning a default name if the input value is empty. The convention for method names is lowercase method name + 'Processor'. ```php class Test extends Validate { protected $rule = [ 'name' => 'nullable|string', ]; protected $preprocessor = [ 'name' => 'setDefaultName', ]; protected function setDefaultNameProcessor(mixed $value) { return empty($value) ? 'Default Name' : $value; } } $data = Test::make()->check([]); var_dump($data); //array(1) { // ["name"]=> // string(12) "Default Name" //} ``` -------------------------------- ### PHP Built-in Type Casting: Object Source: https://v.itwmw.com/en/6/Casts Example of casting a JSON string to a PHP stdClass object using the 'object' type in the `$casts` property. ```PHP protected $casts = ['options' => 'object']; // '{"color":"red"}' -> (object) ['color' => 'red'] ``` -------------------------------- ### PHP - 场景事件配置 (无参数) Source: https://v.itwmw.com/6/Event 展示了如何在验证器的 `$scene` 属性中配置场景事件,当不需要向事件处理类传递参数时,可以直接指定事件类名。例如,在 'add' 场景中,'event' 键关联了 `CheckPermission::class`。 ```php protected $scene = [ 'add' => ['id','user_id','role','event' => CheckPermission::class], ]; ``` -------------------------------- ### PHP Built-in Type Casting: Decimal Source: https://v.itwmw.com/en/6/Casts Example of casting a value to a float with a specified number of decimal places using 'decimal:N' in the `$casts` property. ```PHP protected $casts = [ 'price' => 'decimal:2', // Keep two decimal places 'rate' => 'decimal:4' // Keep four decimal places ]; // '19.99' -> 19.99 // '0.12345' -> 0.1235 ``` -------------------------------- ### PHP 多重类型转换 Source: https://v.itwmw.com/6/Casts 可以为一个字段应用多个转换器,它们将按顺序依次执行,实现组合转换效果。 ```php protected $casts = [ 'options' => ['array', 'json_unicode'] ]; // '[{"name":"虞灪"}]' -> (step 1: array) [['name' => '虞灪']] -> (step 2: json_unicode) '[{"name":"\u865e\u706a"}]' ``` -------------------------------- ### 使用extend方法注册自定义验证闭包 Source: https://v.itwmw.com/5/Rule 通过验证器的`extend`方法,可以动态注册一个自定义验证规则,支持使用闭包函数实现验证逻辑。该方法接收规则名、闭包函数以及可选的错误消息。 ```php class UserValidator extends Validate { } $v = UserValidator::make(); $v->extend("chs",function ($attribute, $value, $parameters, $validator) { return is_scalar($value) && 1 === preg_match('/^[x{4e00}-x{9fa5}]+$/u', (string)$value); }, ':attribute的值只能具有中文'); ``` -------------------------------- ### Get unique items from a collection (PHP) Source: https://v.itwmw.com/5/Collection The `unique` method returns a collection containing only unique items. It can optionally accept a key or a callback to determine uniqueness. It uses loose comparison by default. ```php $collection = validate_collect([1, 1, 2, 2, 3, 4, 2]); $unique = $collection->unique(); $unique->values()->all(); // [1, 2, 3, 4] $collection = validate_collect([ ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], ['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'], ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'], ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'], ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'], ]); $unique = $collection->unique('brand'); $unique->values()->all(); /* [ ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'], ] */ $unique = $collection->unique(function ($item) { return $item['brand'].$item['type']; }); $unique->values()->all(); /* [ ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'], ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'], ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'], ] */ ``` -------------------------------- ### 使用macro扩展Collection类 Source: https://v.itwmw.com/6/Collection 通过 `macro` 方法向 `Itwmw\Validation\Support\Collection\Collection` 类添加新方法。宏闭包可以通过 `$this` 访问集合的其他方法。此示例添加了一个 `toUpper` 方法。 ```php use Itwmw\Validation\Support\Collection\Collection; use Itwmw\Validation\Support\Str; Collection::macro('toUpper', function () { return $this->map(function ($value) { return Str::upper($value); }); }); $collection = validate_collect(['first', 'second']); $upper = $collection->toUpper(); // ['FIRST', 'SECOND'] ``` -------------------------------- ### PHP Built-in Type Casting: JSON Unicode Source: https://v.itwmw.com/en/6/Casts Example of casting a PHP array or object to a Unicode-escaped JSON string using the 'json_unicode' type in the `$casts` property. ```PHP protected $casts = ['properties' => 'json_unicode']; // ['name' => '墨娘'] -> '{"name":"\u58a8\u5a18"}' ``` -------------------------------- ### 使用extendReplacer定义错误消息 Source: https://v.itwmw.com/5/Rule 通过`extendReplacer`方法为自定义规则定义特定的错误消息。可以传入闭包函数或类方法来动态生成错误消息,用于替换默认的错误提示。 ```php $v->extendReplacer('chs', function ($message, $attribute, $rule, $parameters) { return '自定义错误消息'; }); ``` -------------------------------- ### 使用extend方法注册自定义类方法规则 Source: https://v.itwmw.com/5/Rule 除了闭包,`extend`方法还可以接收类名和方法名(字符串格式)来注册一个自定义验证规则。规则方法接收四个参数:属性名、属性值、参数数组和验证器实例。 ```php class Rules { public function chs($attribute, $value, $parameters, $validator) { return is_scalar($value) && 1 === preg_match('/^[x{4e00}-x{9fa5}]+$/u', (string)$value); } } $v->extend("chs","Rules@chs", ':attribute的值只能具有中文'); ``` -------------------------------- ### PHP Type Casting Execution Example Source: https://v.itwmw.com/en/6/Casts Shows how the `check` method applies the defined type casting rules. After validation, specified fields are converted to their target types. ```PHP $v = new TestValidate(); $data = $v->check([ 'name' => 'John Doe', 'age' => '30', 'id' => 123 ]); // The value of $data['age'] will be (int) 30 // The value of $data['id'] will be an instance of UserId ``` -------------------------------- ### max: Get the Maximum Value from a Collection (PHP) Source: https://v.itwmw.com/6/Collection The `max` method returns the maximum value for a given key in the collection. If no key is specified, it returns the maximum scalar value from the collection. Handles both keyed and scalar collections. ```php $max = validate_collect([ ['foo' => 10], ['foo' => 20] ])->max('foo'); // 20 ``` ```php $max = validate_collect([1, 2, 3, 4, 5])->max(); // 5 ``` -------------------------------- ### PHP 验证器类属性 $scene Source: https://v.itwmw.com/6/Validate 定义验证场景,用于指定验证场景对应的验证字段。可以通过类属性$scene或setScene方法设置,支持叠加。 ```php // 类中定义 protected $scene = [ 'login' => ['user', 'pass'] ]; ``` ```php // 使用方法定义 $v->setScene([ 'login' => ['user', 'pass'] ]); ``` -------------------------------- ### 使用extendReplacer关联类方法定义错误消息 Source: https://v.itwmw.com/5/Rule 将自定义错误消息的替换逻辑封装在类方法中,并通过`extendReplacer`方法进行关联。支持实例方法和静态方法,若未指定方法名,则默认使用`replace`方法。 ```php $v->extendReplacer('chs', "Rules@chsMessage"); // 如果为静态方法 $v->extendReplacer('chs', [Rules::class, 'chsMessage']); ``` -------------------------------- ### PHP Custom Class Casting: Simple Class Source: https://v.itwmw.com/en/6/Casts Example of casting a value to a custom class that accepts a single argument in its constructor, using the class name in the `$casts` property. ```PHP // class UserId { public function __construct(protected readonly int $id) {} } protected $casts = ['user_id' => UserId::class]; // 123 -> new UserId(123) ``` -------------------------------- ### PHP Built-in Type Casting: Boolean Source: https://v.itwmw.com/en/6/Casts Example of casting a value to a boolean using the 'bool' type in the `$casts` property. Note the conversion rules for '0', 0, and 'false'. ```PHP protected $casts = ['is_active' => 'bool']; // '1' -> true // 0 -> false ``` -------------------------------- ### 场景事件方法定义 - PHP Source: https://v.itwmw.com/5/Event 展示了如何在验证类内部直接定义场景验证前 (`before`) 和验证后 (`after`) 的事件处理方法,无需单独创建类。方法名遵循 `before` 或 `after` 加方法名的规则。 ```php public function beforeCheckRegisterStatus(array $data) { return true; } ``` -------------------------------- ### Getting strictly unique items from a collection Source: https://v.itwmw.com/6/Collection The `uniqueStrict` method functions identically to the `unique` method, but it performs strict type checking when comparing items for uniqueness. This means that values like integers and their string equivalents will be treated as distinct. ```php $collection = validate_collect([1, '1', 2, '2']); $uniqueStrict = $collection->uniqueStrict(); $uniqueStrict->values()->all(); // [1, '1', 2, '2'] ```