Repository navigation
Expand file tree
/
Copy pathErrorBag.php
More file actions
66 lines (52 loc) · 1.99 KB
/
Copy pathErrorBag.php
File metadata and controls
66 lines (52 loc) · 1.99 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
<?php
namespace BitApps\WPValidator;
class ErrorBag
{
use Helpers;
protected $errors = [];
public function addError($role, $customMessages): void
{
$attributeKey = $role->getInputDataContainer()->getAttributeKey();
$roleName = $role->getRuleName();
$paramValues = $role->getParamValues();
$defaultPlaceholders = [
'attribute' => $role->getInputDataContainer()->getAttributeLabel(),
'value' => $role->getInputDataContainer()->getAttributeValue(),
];
$placeholders = array_merge($paramValues, $defaultPlaceholders);
if (is_string($roleName) && isset($customMessages[$attributeKey . '.' . $roleName])) {
$message = $this->replacePlaceholders($placeholders, $customMessages[$attributeKey . '.' . $roleName]);
} elseif (is_string($roleName) && isset($customMessages[$roleName])) {
$message = $this->replacePlaceholders($placeholders, $customMessages[$roleName]);
} else {
$message = $this->replacePlaceholders($placeholders, $role->message());
}
$this->errors[$attributeKey][] = $message;
}
private function replacePlaceholders(array $placeholders, $message)
{
foreach ($placeholders as $key => $placeholder) {
if (isset($placeholders[$key])) {
if (is_object($placeholder)) {
$placeholder = (array) $placeholder;
}
if (is_array($placeholder)) {
$placeholder = implode(',', $placeholder);
}
$message = str_replace(":" . $key, $placeholder, $message);
}
}
return $message;
}
public function getErrors()
{
return $this->errors;
}
public function hasErrors($field = null): bool
{
if ($field === null) {
return ! empty($this->errors);
}
return isset($this->errors[$field]) && ! empty($this->errors[$field]);
}
}