touhidurabir / command-validator
一个简单的Laravel包,用于验证控制台命令的参数和选项。
1.0.1
2021-09-17 14:43 UTC
Requires
- illuminate/contracts: ^8.61
- illuminate/support: ^8.61
- symfony/console: ^5.3
Requires (Dev)
- orchestra/testbench: ^6.21
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2024-09-17 21:44:06 UTC
README
一个简单的Laravel包,用于验证控制台命令的参数和选项。
安装
使用composer安装/要求该包
composer require touhidurabir/command-validator
使用方法
将特质 HasCommandValidator 放在任何命令中,然后放置验证规则。就是这样。
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Touhidurabir\CommandValidator\HasCommandValidator; class Test extends Command { use HasCommandValidator; /** * The name and signature of the console command. * * @var string */ protected $signature = 'run:test {arg : The command argument} {--opt1= : The command option 1} {--opt2= : The command option 2}'; /** * The command arguments and options validation rules * * @return array */ protected function rules(): array { return [ 'arg' => ['integer', 'required', 'min:100'], 'opt1' => ['integer', 'required', 'max:10'], 'opt2' => ['sometimes', 'nullable', 'string'], ]; } }
此包还支持由Laravel验证本身提供的消息或属性覆盖能力。
要覆盖验证消息,在命令类中放置方法并按需填写
/** * Any custom error message * * @return array */ protected function messages(): array { return []; }
要覆盖验证属性,在命令类中放置方法并按需填写
/** * Any custom arrtibute names to associated with error messages * * @return array */ protected function attributes(): array { return []; }
默认情况下,此验证器在参数或选项验证失败时不会抛出异常,而是以格式化的方式在控制台中打印错误,以便检查缺少/失败的内容。但如果想抛出异常而不是在控制台打印,请覆盖方法 allowValidationFailureOnConsole 并将其返回值设置为 false
/** * Should the validation error print on the console * * @return bool */ protected function allowValidationFailureOnConsole() { return false; }
贡献
欢迎提交拉取请求。对于重大更改,请首先打开一个问题来讨论您想要更改的内容。
请确保适当地更新测试。