StringValidator.php
1.69 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
<?php
namespace YahnisElsts\AdminMenuEditor\Customizable\Validation;
class StringValidator {
private $minLength;
private $maxLength;
private $validationRegex;
/**
* @var bool
*/
private $truncateWithoutError;
/**
* @var false
*/
private $trimWhitespace;
public function __construct(
$minLength = 0,
$maxLength = null,
$truncateWithoutError = false,
$regex = null,
$trimWhitespace = false
) {
$this->minLength = $minLength;
$this->maxLength = $maxLength;
$this->truncateWithoutError = $truncateWithoutError;
$this->validationRegex = $regex;
$this->trimWhitespace = $trimWhitespace;
}
public function __invoke($value, \WP_Error $errors) {
$convertedValue = strval($value);
if ( $this->trimWhitespace ) {
$convertedValue = trim($convertedValue);
}
$length = strlen($convertedValue);
if ( ($this->minLength !== null) && ($length < $this->minLength) ) {
$errors->add('min_length', 'Value is too short, minimum length is ' . $this->minLength);
return $errors;
}
if ( ($this->maxLength !== null) && ($length > $this->maxLength) ) {
if ( $this->truncateWithoutError ) {
$convertedValue = substr($convertedValue, 0, $this->maxLength);
} else {
$errors->add('max_length', 'Value is too long, maximum length is ' . $this->maxLength);
return $errors;
}
}
if ( $this->validationRegex !== null ) {
if ( !preg_match($this->validationRegex, $convertedValue) ) {
$errors->add(
'regex_match_failed',
'Value must match the following regex: ' . $this->validationRegex
);
return $errors;
}
}
return $convertedValue;
}
public static function sanitizeStripTags($value) {
return wp_strip_all_tags((string) $value);
}
}