NumericSetting.php
1.91 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
71
72
73
74
75
76
77
78
79
80
81
<?php
namespace YahnisElsts\AdminMenuEditor\Customizable\Settings;
use YahnisElsts\AdminMenuEditor\Customizable\Storage\StorageInterface;
abstract class NumericSetting extends Setting {
protected $defaultValue = 0;
/**
* @var null|float|int
*/
protected $minValue = null;
/**
* @var null|float|int
*/
protected $maxValue = null;
public function __construct($id, StorageInterface $store = null, $params = []) {
parent::__construct($id, $store, $params);
$this->minValue = isset($params['minValue']) ? $params['minValue'] : $this->minValue;
$this->maxValue = isset($params['maxValue']) ? $params['maxValue'] : $this->maxValue;
}
public function validate($errors, $value, $stopOnFirstError = false) {
if ( $this->canTreatAsNull($value) ) {
return null;
}
if ( !is_numeric($value) ) {
$errors->add('not_numeric', 'Value must be a number');
return $errors;
}
$numValue = floatval($value);
if ( ($this->minValue !== null) && ($numValue < $this->minValue) ) {
$errors->add('min_value', 'Value must be ' . $this->minValue . ' or greater');
}
if ( ($this->maxValue !== null) && ($numValue > $this->maxValue) ) {
$errors->add('max_value', 'Value must be ' . $this->maxValue . ' or less');
}
if ( $errors->has_errors() ) {
return $errors;
}
return $numValue;
}
/**
* @return float|int|null
*/
public function getMinValue() {
return $this->minValue;
}
/**
* @return float|int|null
*/
public function getMaxValue() {
return $this->maxValue;
}
public function serializeValidationRules() {
$result = [];
if ( $this->isNullable() ) {
$result['isNullable'] = true;
$result['convertEsToNull'] = true;
}
$parserConfig = [];
if ( $this->minValue !== null ) {
$parserConfig['min'] = $this->minValue;
}
if ( $this->maxValue !== null ) {
$parserConfig['max'] = $this->maxValue;
}
$result['parsers'] = [['numeric', $parserConfig]];
return $result;
}
}