perryvandermeer/laravel-console-validator

验证Laravel命令的参数

1.1.0 2024-08-07 12:48 UTC

This package is auto-updated.

Last update: 2024-09-23 12:04:08 UTC


README

Latest Version on Packagist GitHub Pest Action Status GitHub Pint Status Total Downloads

此包允许您轻松验证在Laravel命令中输入的所有参数。

laravel-console-validator

以下是一个简短的示例,我们将自动验证foo参数是否满足requiredmin:3规则

<?php
 
namespace App\Console\Commands;
 
use Illuminate\Console\Command;
use PerryvanderMeer\LaravelConsoleValidator\ValidatesArguments;
 
class ExampleCommand extends Command
{
    use ValidatesArguments;
    
    /**
     * Set the validation rules that apply to the command.
     *
     * @var array<string, array|string>
     */
    protected array $rules = [
        'foo' => ['required', 'min:3'],
    ];
}

需求

此包需要PHP 8.1+和Laravel 10+。

安装

您可以通过composer安装此包

composer require perryvandermeer/laravel-console-validator

使用

要开始使用,您需要在您的命令中包含ValidatesArguments特质。
当命令执行时,它将自动在到达handle()方法之前执行验证。如果验证失败,则handle()方法将永远不会被执行。

<?php
 
namespace App\Console\Commands;
 
use Illuminate\Console\Command;
use PerryvanderMeer\LaravelConsoleValidator\ValidatesArguments;
 
class ExampleCommand extends Command
{
    use ValidatesArguments;
}

配置验证器

就像使用Laravel的验证器一样,您可以通过配置规则、消息和属性来配置它。

规则

您可以通过定义$rules属性和/或rules()方法来配置命令使用的验证规则。

rules()方法在您尝试使用在数组属性中不受支持的运行时语法时非常有用,例如Laravel规则对象,如Rule::password()。当您同时使用$rules属性和rules()方法时,我们将它们合并在一起。

属性和/或方法应返回一个参数/规则对的数组及其相应的验证规则。

/**
 * Set the validation rules that apply to the command.
 *
 * @var array<string, array|string>
 */
protected array $rules = [
    'title' => ['required', 'min:3'],
    'content' => 'required',
];
/**
 * Get the validation rules that apply to the command.
 *
 * @return array<string, \Illuminate\Contracts\Validation\Rule|array|string>
 */
protected function rules() : array
{
    return [
        'title' => ['required', 'min:3', Rule::unique('posts')],
        'content' => 'required',
    ];
}

消息

您可以通过定义$messages属性和/或messages()方法来自定义命令使用的错误消息。

messages()方法在您尝试使用在数组属性中不受支持的运行时语法时非常有用。当您同时使用$messages属性和messages()方法时,我们将它们合并在一起。

属性和/或方法应返回一个参数/规则对的数组及其相应的错误消息。

/**
 * Set the error messages for the defined validation rules.
 *
 * @var array<string, string>
 */
protected array $messages = [
    'title' => 'Whoo general message for title argument..!',
    'content.min' => 'Hmm the content is very short..!',
];
/**
 * Get the error messages for the defined validation rules.
 *
 * @return array<string, string>
 */
protected function messages() : array
{
    return [
        'title' => 'Whoo general message for title argument..!',
        'content.min' => 'Hmm the content is very short..!',
    ];   
}

属性

许多Laravel内置的验证规则错误消息包含一个:attribute占位符。默认情况下,参数的名称用作:attribute。如果您希望验证消息中的:attribute占位符被自定义属性名称替换,您可以定义自定义名称,通过定义$attributes属性和/或attributes()方法。

attributes()方法在您尝试使用在数组属性中不受支持的运行时语法时非常有用。当您同时使用$attributes属性和attributes()方法时,我们将它们合并在一起。

属性和/或方法应返回一个参数/名称对的数组。

/**
 * Set custom attributes for validator errors.
 *
 * @return array<string, string>
 */
protected array $attributes = [
    'title' => 'custom title',
    'content' => 'custom content',
];
/**
 * Get custom attributes for validator errors.
 *
 * @return array<string, string>
 */
protected function attributes() : array
{
    return [
        'title' => 'custom title',
        'content' => 'custom content',
    ];
}

为验证准备参数

如果您需要在应用验证规则之前准备或清理任何数据,您可以使用prepareForValidation()方法。

/**
 * Prepare the data for validation.
 */
protected function prepareForValidation() : void
{
     $this->input->setArgument(
        name: 'foo',
        value: "{$this->argument('foo')}-bar",
    );
}

处理已验证参数

就像使用 Laravel 的验证器一样,您可以在实现的其他部分中使用验证过的参数。

检索所有验证过的参数

在验证参数后,您可能希望检索实际经过验证的参数。这可以通过几种方式实现。首先,您可以在您的命令中调用 validated() 方法。此方法返回一个包含已验证数据的数组。

$this->validated(); // (array) ['foo' => 'bar', 'bar' => 'baz']

当您想要一个包含所有经过验证的参数的 集合 时,您可以在您的命令中调用 collect() 方法。此方法返回一个包含已验证数据的 集合

$this->collect(); // collect(['foo' => 'bar', 'bar' => 'baz'])

检索单个验证过的参数

当您向 validated() 方法传递一个参数时,它只会返回该参数的验证值。如果请求的参数尚未验证,它将抛出 UnvalidatedArgumentException 异常。

$this->validated('foo'); // (string) 'bar'

当您想确保参数的验证值被转换为字符串时,您可以使用 string() 方法。

$this->string('foo'); // (string) 'bar'

您的命令可能接收实际上是字符串的“真值”,例如 (string) 'true'(string) 'on'。您可以使用 bool()boolean() 方法将这些值作为布尔值检索。这些方法使用 PHP 的 FILTER_VALIDATE_BOOLEAN 标志来确定传递的参数是 (bool) true 还是 (bool) false

$this->boolean('foo'); // (bool) false

测试

当使用版本高于 11.9.0laravel/framework 时,您可以使用自定义的 assertFailedWithValidationError() 方法来断言命令返回了任何验证错误。

use Symfony\Component\Console\Command\Command;

$this->artisan('foo')
    ->assertFailedWithValidationError();

当使用 laravel/framework 的较低版本时,您可以使用 assertExitCode() 方法来断言命令返回了任何验证错误。

use Symfony\Component\Console\Command\Command;

$this->artisan('foo')
    ->assertExitCode(Command::INVALID);

此外,测试特定的验证错误可能很有用。您可以使用 expectsOutput() 方法来断言命令返回了特定的验证错误。

$this->artisan('foo')
    ->expectsOutput('The foo field must be at least 6 characters.') 

贡献

有关详细信息,请参阅 CONTRIBUTING

安全漏洞

有关如何报告安全漏洞,请参阅我们的 安全策略

鸣谢

许可

MIT 许可证 (MIT)。有关更多信息,请参阅 许可文件