php 扩展/覆盖Laravel验证程序类

9ceoxa92  于 2023-02-21  发布在  PHP
关注(0)|答案(3)|浏览(106)

在Laravel 8.3中,他们引入了一个新特性,stopOnFirstFailure,它可以在规则失败时完全停止验证。我希望在Laravel 7中使用这个特性。在检查Laravel 8的***vendor/laravel/framework/src/Validation/Validator.php***时,我发现***stopOnFirstFailure***只是在***Validator.php***的***passes***函数中添加了一个if语句,如果受保护的变量***stopOnFirstFailure***是真的。在Laravel 7中是否可以通过扩展/覆盖Validator.php类来实现这些?我一直在研究扩展核心Laravel类,偶然发现了这个article,但它有点令人困惑,因为这篇文章只介绍了如何覆盖特定的函数。在我的例子中,我需要声明一个受保护的变量,覆盖一个函数,并声明一个新函数。
Laravel 8验证器. php代码:
声明变量:

/**
     * Indicates if the validator should stop on the first rule failure.
     *
     * @var bool
     */
    protected $stopOnFirstFailure = false;

***第一次故障时停止***功能:

/**
     * Instruct the validator to stop validating after the first rule failure.
     *
     * @param  bool  $stopOnFirstFailure
     * @return $this
     */
    public function stopOnFirstFailure($stopOnFirstFailure = true)
    {
        $this->stopOnFirstFailure = $stopOnFirstFailure;

        return $this;
    }

***通过***函数:

/**
     * Determine if the data passes the validation rules.
     *
     * @return bool
     */
    public function passes()
    {
        $this->messages = new MessageBag;

        [$this->distinctValues, $this->failedRules] = [[], []];

        // We'll spin through each rule, validating the attributes attached to that
        // rule. Any error messages will be added to the containers with each of
        // the other error messages, returning true if we don't have messages.
        foreach ($this->rules as $attribute => $rules) {
            if ($this->shouldBeExcluded($attribute)) {
                $this->removeAttribute($attribute);

                continue;
            }

            if ($this->stopOnFirstFailure && $this->messages->isNotEmpty()) {
                break;
            }

            foreach ($rules as $rule) {
                $this->validateAttribute($attribute, $rule);

                if ($this->shouldBeExcluded($attribute)) {
                    $this->removeAttribute($attribute);

                    break;
                }

                if ($this->shouldStopValidating($attribute)) {
                    break;
                }
            }
        }

编辑:验证器在我的代码中被窗体请求使用。我的代码示例:

class UpdateRegistrationTagsRequest extends FormRequest
{
    protected $stopOnFirstFailure = true;
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'product_id' => ['required'],
            'product.*.type' => ['required','distinct'],
            'product.*.value' => ['required'],
            'product' => ['bail', 'required', 'array', new CheckIfArrayOfObj, new CheckIfProductTypeExists($this->product_id)]
        ];
    }

    protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
    {
        $response = new JsonResponse(['api' => [
            'header' => [
                'message' => 'The given data is invalid', 
                'errors' => $validator->errors()->first()   
            ],
            'body' => ''
                ]], 422);

        throw new \Illuminate\Validation\ValidationException($validator, $response);
    }
}

编辑:遵循@ thefalled的建议,下面是我所做的.我的CustomValidator.php类在应用程序目录内的CustomClass中:

<?php 

namespace App\CustomClass;
use Illuminate\Validation\Validator;
use Illuminate\Support\MessageBag;

class CustomValidator extends Validator
{
    /**
     * Indicates if the validator should stop on the first rule failure.
     *
     * @var bool
     */
    protected $stopOnFirstFailure = true;

     /**
     * Instruct the validator to stop validating after the first rule failure.
     *
     * @param  bool  $stopOnFirstFailure
     * @return $this
     */
    public function stopOnFirstFailure($stopOnFirstFailure = true)
    {
        $this->stopOnFirstFailure = $stopOnFirstFailure;

        return $this;
    }

    /**
     * Determine if the data passes the validation rules.
     *
     * @return bool
     */
    public function passes()
    {
        $this->messages = new MessageBag;

        [$this->distinctValues, $this->failedRules] = [[], []];

        // We'll spin through each rule, validating the attributes attached to that
        // rule. Any error messages will be added to the containers with each of
        // the other error messages, returning true if we don't have messages.
        foreach ($this->rules as $attribute => $rules) {
            if ($this->shouldBeExcluded($attribute)) {
                $this->removeAttribute($attribute);

                continue;
            }

            if ($this->stopOnFirstFailure && $this->messages->isNotEmpty()) {
                break;
            }

            foreach ($rules as $rule) {
                $this->validateAttribute($attribute, $rule);

                if ($this->shouldBeExcluded($attribute)) {
                    $this->removeAttribute($attribute);

                    break;
                }

                if ($this->shouldStopValidating($attribute)) {
                    break;
                }
            }
        }
        return parent::passes();
    }
}

CustomClass文件夹中的我的验证器工厂

<?php 

namespace App\CustomClass;
use Illuminate\Validation\Factory;
use App\CustomClass\CustomValidator;

class ValidatorFactory extends Factory
{
    protected function resolve( array $data, array $rules, array $messages, array $customAttributes )
    {
        if (is_null($this->resolver)) {
            return new CustomValidator($this->translator, $data, $rules, $messages, $customAttributes);
        }

        return call_user_func($this->resolver, $this->translator, $data, $rules, $messages, $customAttributes);
    }
}

我的应用程序服务提供程序:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\CustomClass\ValidatorFactory;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->extend('validator', function () {
            return $this->app->get(ValidatorFactory::class);
        });
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}
lb3vh1jj

lb3vh1jj1#

你基本上需要扩展验证器来修改那个方法,然后创建你自己的验证工厂来创建这个新的验证器,而不是默认的验证器。

use Illuminate\Validation\Validator;

class CustomValidator extends Validator
{
    public function passes()
    {
        //TODO make changes on that loop
        return parent::passes();
    }
}

然后你需要一个验证工厂来创建这个新的类,这也会扩展默认的类:

use Illuminate\Validation\Factory;

class ValidatorFactory extends Factory
{
    protected function resolve( array $data, array $rules, array $messages, array $customAttributes )
    {
        if (is_null($this->resolver)) {
            return new CustomValidator($this->translator, $data, $rules, $messages, $customAttributes);
        }

        return call_user_func($this->resolver, $this->translator, $data, $rules, $messages, $customAttributes);
    }
}

最后,在register()方法的app/Providers/AppServiceProvider.php中,您需要将默认工厂与自定义工厂交换:

$this->app->extend('validator', function () {
    return $this->app->get(ValidatorFactory::class);
});

注意,validatorIlluminate\Validation\Factory的绑定(或别名)的名称,您应该可以对验证器进行任何更改。

nnvyjq4y

nnvyjq4y2#

可能有点晚了,但是我在Laravel 6上遇到了同样的问题。我不想扩展/覆盖验证程序的当前正常行为。所以我这样做了

public function validateResolved()
{
    if (!$this->authorize()) {
        $this->failedAuthorization();
    }
    foreach ($this->rules() as $key=>$val) {
        $validator = app('validator')->make(
            request()->all(),
            [$key=>$val],
            $this->messages()
        );
        if ($validator->fails()) {
            throw \Illuminate\Validation\ValidationException::withMessages($validator->errors()->messages());
        }
    }
}
mwecs4sa

mwecs4sa3#

来自laracasts的用户@davestewart的回答:
使用(解析)自定义验证器的正确方法应该是使用Validator::resolver方法:

App::make('validator')->resolver(function($translator, $data, $rules, $messages)
{
    // return your custom validator here
    return new MyCustomValidator($translator, $data, $rules, $messages);
});

理论上,当FormRequest类调用getValidatorInstance()时,它应该解析您的自定义验证器。
我个人的感觉是,这是一个非常脆弱的做事方式,但我只使用了9个月左右的框架,所以我期待有很好的理由,使它如此-坦率地说-错综复杂。
P.S.该实现在商业项目上进行了测试,完全满足要求

相关问题