/
AbstractTranslatableValidator.php
102 lines (89 loc) · 2.59 KB
/
AbstractTranslatableValidator.php
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
<?php
namespace Concrete\Core\Validator;
use Closure;
use InvalidArgumentException;
/**
* Abstract class for managing translatable requirements and errors.
*/
abstract class AbstractTranslatableValidator implements TranslatableValidatorInterface
{
/**
* @var array
*/
protected $translatable_requirements = [];
/**
* @var array
*/
protected $translatable_errors = [];
/**
* {@inheritdoc}
*
* @see \Concrete\Core\Validator\TranslatableValidatorInterface::setRequirementString()
*/
public function setRequirementString($code, $message)
{
if (!$this->isTranslatableStringValueValid($message)) {
throw new InvalidArgumentException('Invalid translatable string value provided for Validator');
}
$this->translatable_requirements[$code] = $message;
}
/**
* {@inheritdoc}
*
* @see \Concrete\Core\Validator\TranslatableValidatorInterface::setErrorString()
*/
public function setErrorString($code, $message)
{
if (!$this->isTranslatableStringValueValid($message)) {
throw new InvalidArgumentException('Invalid translatable string value provided for Validator');
}
$this->translatable_errors[$code] = $message;
}
/**
* {@inheritdoc}
*
* @see \Concrete\Core\Validator\ValidatorInterface::getRequirementStrings()
*/
public function getRequirementStrings()
{
$map = $this->translatable_requirements;
foreach ($map as $key => &$value) {
if ($value instanceof Closure) {
$value = $value($this, $key);
}
}
return $map;
}
/**
* Get an error string given a code and a passed value.
*
* @param int $code
* @param mixed $value
* @param mixed $default
*
* @return string|mixed Returns a string or $default
*/
protected function getErrorString($code, $value, $default = null)
{
if (array_key_exists($code, $this->translatable_errors)) {
$resolver = $this->translatable_errors[$code];
if ($resolver instanceof Closure) {
return $resolver($this, $code, $value);
} else {
return $resolver;
}
}
return $default;
}
/**
* Check to see if $value a valid stand in for a translatable string.
*
* @param \Closure|string|mixed $value
*
* @return bool
*/
protected function isTranslatableStringValueValid($value)
{
return $value instanceof Closure || is_string($value);
}
}