/
MaximumLengthValidator.php
91 lines (80 loc) · 2.12 KB
/
MaximumLengthValidator.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
<?php
namespace Concrete\Core\Validator\String;
use ArrayAccess;
use Concrete\Core\Validator\AbstractTranslatableValidator;
use InvalidArgumentException;
/**
* Validate the length of a string.
*/
class MaximumLengthValidator extends AbstractTranslatableValidator
{
/**
* Too long.
*
* @var int
*/
const E_TOO_LONG = 1;
/**
* The maximum length.
*
* @var int
*/
protected $maximum_length;
/**
* MaximumLengthValidator constructor.
*
* @param int $maximum_length
*/
public function __construct($maximum_length)
{
$this->maximum_length = $maximum_length;
$this->setRequirementString(
self::E_TOO_LONG,
function (MaximumLengthValidator $validator, $code) {
return t('Must be at most %s characters long.', $validator->getMaximumLength());
}
);
$this->setErrorString(
self::E_TOO_LONG,
function (MaximumLengthValidator $validator, $code, $mixed) {
return t('String "%s" must be at most %s characters long.', $mixed, $validator->getMaximumLength());
}
);
}
/**
* Get the maximum length allowed.
*
* @return int
*/
public function getMaximumLength()
{
return $this->maximum_length;
}
/**
* Set the maximum length allowed.
*
* @param int $maximum_length
*/
public function setMaximumLength($maximum_length)
{
$this->maximum_length = $maximum_length;
}
/**
* {@inheritdoc}
*
* @see \Concrete\Core\Validator\ValidatorInterface::isValid()
*/
public function isValid($mixed, ArrayAccess $error = null)
{
if ($mixed !== null && !is_string($mixed)) {
throw new InvalidArgumentException(t('Invalid type supplied to validator.'));
}
if ($this->getMaximumLength() < strlen($mixed)) {
if ($error && $message = $this->getErrorString(self::E_TOO_LONG, $mixed)) {
$error[] = $message;
}
return false;
}
return true;
}
}