1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ntentan\utils\validator\validations; |
4
|
|
|
use ntentan\utils\validator\Validation; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* Validates the length of a field. |
8
|
|
|
* |
9
|
|
|
* @package ntentan\utils\validator\validations |
10
|
|
|
*/ |
11
|
|
|
class LengthValidation extends Validation |
12
|
|
|
{ |
13
|
4 |
|
public function run($field, $data) |
14
|
|
|
{ |
15
|
4 |
|
$value = $this->getFieldValue($field, $data); |
16
|
4 |
|
$length = strlen($value); |
17
|
4 |
|
if (is_array($field['options'])) { |
18
|
2 |
|
$hasMin = isset($field['options']['min']); |
19
|
2 |
|
$hasMax = isset($field['options']['max']); |
20
|
2 |
|
$max = $field['options']['max']; |
21
|
2 |
|
$min = $field['options']['min']; |
22
|
2 |
|
return $this->evaluateResult( |
23
|
2 |
|
$field, |
24
|
2 |
|
($hasMax ? $length <= $max : true) && |
25
|
2 |
|
($hasMin ? $length >= $min : true), |
26
|
2 |
|
$this->getLenghtValidationMessage($field['name'], $hasMin, $hasMax, $min, $max) |
27
|
2 |
|
); |
28
|
|
|
} else { |
29
|
2 |
|
return $this->evaluateResult( |
30
|
2 |
|
$field, |
31
|
2 |
|
$length <= $field['options'], |
32
|
2 |
|
"The length of the {$field['name']} field must be {$field['options']} characters or less" |
33
|
2 |
|
); |
34
|
|
|
} |
35
|
|
|
} |
36
|
|
|
|
37
|
2 |
|
private function getLenghtValidationMessage($name, $hasMin, $hasMax, $min, $max) |
38
|
|
|
{ |
39
|
2 |
|
return "The length of the {$name} field must be" . |
40
|
2 |
|
($hasMin ? " $min characters or greater" : '') . |
41
|
2 |
|
($hasMax && $hasMin ? " and" : '') . |
42
|
2 |
|
($hasMax ? " $max characters or lesser" : ''); |
43
|
|
|
} |
44
|
|
|
} |