gpt4 book ai didi

php - 如何获取 Laravel Controller 方法的所有可能的错误消息

转载 作者:行者123 更新时间:2023-12-02 00:47:32 25 4
gpt4 key购买 nike

所以我有一个 Laravel 应用程序,它有许多 Controller 来处理应用程序的各个方面。

现在每个 Controller 都有不同的方法。大多数方法都定义了验证规则,例如:

$validationArray = [
'id'=>'required|integer',
'status'=>'required|string'
];
$validator = Validator::make($request->all(),$validationArray);
if ($validator->fails()){
return Response::json(['response'=>implode(', ',$validator->messages()->all())],422);
}

现在是以下行:

return Response::json(['response'=>implode(', ',$validator->messages()->all())],422);

实际上返回验证规则中的任何错误。

我的问题是:有没有办法以编程方式获取所有可能的错误消息?

当然,一种方法是逐条规则地进行操作并手动创建列表,但有数百种方法分散在各个 Controller 中。

因此,如果有人能指出我以某种更简单的方式获取所有错误消息的方向,我将不胜感激。

提前谢谢您!

更新

因此,为了进一步清除,我需要一个所有可能错误的列表,就像上面的代码一样,列表如下:

['id is required', 'id must be an integer', 'status is required', 'status must be an string']

更新2

请记住,有数百种方法,而且我不想更改方法的最终响应,而是希望有某种外部脚本可以帮助我获取错误消息,而不会过多干扰 Controller 。

最佳答案

为了做到这一点,您必须扩展 Validator 类并编写一个方法来迭代所有规则并显式添加错误消息,就像它们失败一样。

首先,创建一个新文件app\Http\Custom\Validator.php:

<?php

namespace App\Http\Custom;

use Illuminate\Contracts\Validation\Rule as RuleContract;
use Illuminate\Support\MessageBag;
use Illuminate\Validation\ValidationRuleParser;
use Illuminate\Validation\Validator as BaseValidator;

class Validator extends BaseValidator {

/** @var MessageBag */
protected $errorMessages;

/** @var array */
protected $hasExplicitFileErrorMessage;

protected $explicitFileRules = [
'File', 'Image', 'Mimes', 'Mimetypes', 'Dimensions',
];

function availableErrors()
{
$this->errorMessages = new MessageBag();
$this->hasExplicitFileErrorMessage = [];

foreach($this->rules as $attribute => $rules) {
$attribute = str_replace('\.', '->', $attribute);
foreach($rules as $rule) {
[$rule, $parameters] = ValidationRuleParser::parse($rule);

if($rule == '') {
continue;
}
if(($keys = $this->getExplicitKeys($attribute)) &&
$this->dependsOnOtherFields($rule)) {
$parameters = $this->replaceAsterisksInParameters($parameters, $keys);
}
// explicitly add "failed to upload" error
if($this->hasRule($attribute, $this->explicitFileRules) && !in_array($attribute, $this->hasExplicitFileErrorMessage)) {
$this->addFailureMessage($attribute, 'uploaded', []);
$this->hasExplicitFileErrorMessage[] = $attribute;
}

if($rule instanceof RuleContract) {
$messages = $rule->message() ? (array)$rule->message() : [get_class($rule)];
foreach($messages as $message) {
$this->addFailureMessage($attribute, get_class($rule), [], $message);
}
} else {
$this->addFailureMessage($attribute, $rule, $parameters);
}
}
}

return $this->errorMessages->all();
}

function addFailureMessage($attribute, $rule, $parameters = [], $rawMessage = null)
{
$this->errorMessages->add($attribute, $this->makeReplacements(
$rawMessage ?? $this->getMessage($attribute, $rule), $attribute, $rule, $parameters
));
}

// we have to override this method since file-type errors depends on data value rather than rule type
protected function getAttributeType($attribute)
{
if($this->hasRule($attribute, $this->explicitFileRules)) {
return 'file';
}
return parent::getAttributeType($attribute);
}
}

接下来,让我们在验证工厂中注册此类:

<?php

namespace App\Providers;

use App\Http\Custom\Validator; // <-- our custom validator
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider {

public function boot()
{
app('validator')->resolver(function ($translator, $data, $rules, $messages) {
return new Validator($translator, $data, $rules, $messages);
});
}

}

而且...仅此而已。让我们测试一下:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class HomeController extends Controller {

function index(Request $request)
{
$rules = [
'id' => 'required|int|between:2,10',
'status' => 'required_with:nonexisting|string|email',
'avatar' => 'required|file|mimes:png|max:1000',
'company' => 'required_without:id|unique:companies,id'
];

$validator = Validator::make([], $rules);

dump($validator->availableErrors());
}

}
array:13 [▼
0 => "The id field is required."
1 => "The id must be an integer."
2 => "The id must be between 2 and 10."
3 => "The status field is required when nonexisting is present."
4 => "The status must be a string."
5 => "The status must be a valid email address."
6 => "The avatar failed to upload."
7 => "The avatar field is required."
8 => "The avatar must be a file."
9 => "The avatar must be a file of type: png."
10 => "The avatar may not be greater than 1000 kilobytes."
11 => "The company field is required when id is not present."
12 => "The company has already been taken."
]

关于php - 如何获取 Laravel Controller 方法的所有可能的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58317399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com