forked from inhere/php-validate
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathErrorMessageTrait.php
More file actions
457 lines (403 loc) · 10.2 KB
/
ErrorMessageTrait.php
File metadata and controls
457 lines (403 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
<?php declare(strict_types=1);
namespace Inhere\Validate\Traits;
use Inhere\Validate\Helper;
use Inhere\Validate\Validator\GlobalMessage;
use Inhere\Validate\Validators;
use function array_merge;
use function array_pop;
use function array_shift;
use function count;
use function implode;
use function is_array;
use function is_int;
use function is_string;
use function strtr;
/**
* trait ErrorMessageTrait
*
* @author inhere
* @package Inhere\Validate\Traits
*/
trait ErrorMessageTrait
{
/**
* error messages map
*
* @var array
*/
private array $_messages = [];
/**
* attribute field translate list
*
* @var array
*/
private array $_translates = [];
/**
* Save all validation error messages
*
* [
* ['name' => 'field', 'msg' => 'error Message1' ],
* ['name' => 'field2', 'msg' => 'error Message2' ],
* ]
*
* @var array[]
*/
private array $_errors = [];
/**
* Whether there is error stop validation 是否出现验证失败就立即停止验证
* True -- 出现一个验证失败即停止验证,并退出
* False -- 全部验证并将错误信息保存到 {@see $_errors}
*
* @var boolean
*/
private bool $_stopOnError = true;
/**
* Prettify field name on get error message
*
* @var bool
*/
private bool $_prettifyName = true;
protected function prepareValidation(): void
{
// error message
$this->_messages = array_merge($this->messages(), $this->_messages);
// field translate
$this->_translates = array_merge($this->translates(), $this->_translates);
}
/*******************************************************************************
* Errors Information
******************************************************************************/
/**
* @return bool
*/
protected function shouldStop(): bool
{
return $this->isFail() && $this->_stopOnError;
}
/**
* Is there an error?
*
* @return boolean
*/
public function hasError(): bool
{
return $this->isFail();
}
/**
* @return bool
*/
public function isFail(): bool
{
return count($this->_errors) > 0;
}
/**
* @return bool
*/
public function failed(): bool
{
return $this->isFail();
}
/**
* @return bool
* @deprecated will delete, please use isOk() or isPassed() instead
*/
public function ok(): bool
{
return !$this->isFail();
}
/**
* @return bool
*/
public function isOk(): bool
{
return !$this->isFail();
}
/**
* @return bool
* @deprecated will delete, please use isOk() or isPassed() instead
*/
public function passed(): bool
{
return !$this->isFail();
}
/**
* @return bool
*/
public function isPassed(): bool
{
return !$this->isFail();
}
/**
* check field whether in the errors
*
* @param string $field
*
* @return bool
*/
public function inError(string $field): bool
{
foreach ($this->_errors as $item) {
if ($field === $item['name']) {
return true;
}
}
return false;
}
/**
* @param string $field
* @param string $msg
*/
public function addError(string $field, string $msg): void
{
$this->_errors[] = [
'name' => $field,
'msg' => $msg,
];
}
/**
* @param string $field Only get errors of the field.
*
* @return array
*/
public function getErrors(string $field = ''): array
{
if ($field) {
$errors = [];
foreach ($this->_errors as $item) {
if ($field === $item['name']) {
$errors[] = $item['msg'];
}
}
return $errors;
}
return $this->_errors;
}
/**
* clear errors
*/
public function clearErrors(): void
{
$this->_errors = [];
}
/**
* Get the first error message
*
* @param bool $onlyMsg
*
* @return array|string
*/
public function firstError(bool $onlyMsg = true): array|string
{
if (!$errors = $this->_errors) {
return $onlyMsg ? '' : [];
}
$first = array_shift($errors);
return $onlyMsg ? $first['msg'] : $first;
}
/**
* Get the last error message
*
* @param bool $onlyMsg
*
* @return array|string
*/
public function lastError(bool $onlyMsg = true): array|string
{
if (!$errors = $this->_errors) {
return $onlyMsg ? '' : [];
}
$last = array_pop($errors);
return $onlyMsg ? $last['msg'] : $last;
}
/**
* @param mixed|null $_stopOnError
*
* @return static
*/
public function setStopOnError(mixed $_stopOnError = null): static
{
if (null !== $_stopOnError) {
$this->_stopOnError = (bool)$_stopOnError;
}
return $this;
}
/**
* @return bool
*/
public function isStopOnError(): bool
{
return $this->_stopOnError;
}
/*******************************************************************************
* Error Messages
******************************************************************************/
/**
* @param string $key
* @param array|string $message
*/
public function setMessage(string $key, array|string $message): void
{
if ($key && $message) {
$this->_messages[$key] = $message;
}
}
/**
* @return array
*/
public function getMessages(): array
{
return $this->_messages;
}
/**
* @param array $messages
*
* @return static
*/
public function setMessages(array $messages): static
{
foreach ($messages as $key => $value) {
$this->setMessage($key, $value);
}
return $this;
}
/**
* 各个验证器的提示消息
*
* @param callable|string $validator 验证器
* @param string $field
* @param array $args
* @param array|string|null $message 自定义提示消息
*
* @return string
*/
public function getMessage(callable|string $validator, string $field, array $args = [], null|array|string $message = null): string
{
$rawName = is_string($validator) ? $validator : 'callback';
$params = [
'{attr}' => $this->getTranslate($field)
];
// get message from built in dict.
if (!$message) {
$message = $this->findMessage($field, $rawName) ?: GlobalMessage::getDefault();
// is array. It's defined multi error messages
} elseif (is_array($message)) {
$message = $message[$field] ?? $message[$rawName] ?? $this->findMessage($field, $rawName);
if (!$message) { // use default
return strtr(GlobalMessage::getDefault(), $params);
}
}
/** @see GlobalMessage::$messages['size'] */
if (is_array($message)) {
$msgKey = count($args);
$message = $message[$msgKey] ?? $message[0];
}
if (!str_contains($message, '{')) {
return $message;
}
foreach ($args as $key => $value) {
$key = is_int($key) ? "value$key" : $key;
// build params
$params['{' . $key . '}'] = is_array($value) ? implode(',', $value) : $value;
}
return strtr($message, $params);
}
/**
* @param string $field
* @param string $rawName
*
* @return string|array
*/
protected function findMessage(string $field, string $rawName): array|string
{
// allow define a message for a validator.
// eg: 'username.required' => 'some message ...'
$fullKey = $field . '.' . $rawName;
$realName = Validators::realName($rawName);
// get from default
if (!$this->_messages) {
return GlobalMessage::get($realName);
}
if (isset($this->_messages[$fullKey])) {
$message = $this->_messages[$fullKey];
// eg 'required' => 'some message ...'
} elseif (isset($this->_messages[$rawName])) {
$message = $this->_messages[$rawName];
} elseif (isset($this->_messages[$realName])) {
$message = $this->_messages[$realName];
} else { // get from default
$message = GlobalMessage::get($realName);
}
return $message;
}
/**
* set the attrs translation data
*
* @param array $fieldTrans
*
* @return static
*/
public function setTranslates(array $fieldTrans): static
{
return $this->addTranslates($fieldTrans);
}
/**
* add the attrs translation data
*
* @param array $fieldTrans
*
* @return static
*/
public function addTranslates(array $fieldTrans): static
{
foreach ($fieldTrans as $field => $tran) {
$this->_translates[$field] = $tran;
}
return $this;
}
/**
* @return array
*/
public function getTranslates(): array
{
return $this->_translates;
}
/**
* get field translate string.
*
* @param string $field
*
* @return string
*/
public function getTranslate(string $field): string
{
$trans = $this->getTranslates();
if (isset($trans[$field])) {
return $trans[$field];
}
if ($this->_prettifyName) {
return Helper::prettifyFieldName($field);
}
return $field;
}
/**
* @return array
*/
public function clearTranslates(): array
{
return $this->_translates = [];
}
/**
* @return bool
*/
public function isPrettifyName(): bool
{
return $this->_prettifyName;
}
/**
* @param bool $prettifyName
*/
public function setPrettifyName(bool $prettifyName = true): void
{
$this->_prettifyName = $prettifyName;
}
}