1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10:
11:
12: namespace Chromabits\Nucleus\Validation\Constraints;
13:
14: use Chromabits\Nucleus\Meditation\Arguments;
15: use Chromabits\Nucleus\Meditation\Boa;
16: use Chromabits\Nucleus\Meditation\Constraints\AbstractConstraint;
17: use Chromabits\Nucleus\Meditation\Exceptions\InvalidArgumentException;
18: use Chromabits\Nucleus\Support\Std;
19:
20: 21: 22: 23: 24: 25:
26: class StringLengthConstraint extends AbstractConstraint
27: {
28: 29: 30:
31: protected $min;
32:
33: 34: 35:
36: protected $max;
37:
38: 39: 40:
41: public function getMin()
42: {
43: return $this->min;
44: }
45:
46: 47: 48:
49: public function getMax()
50: {
51: return $this->max;
52: }
53:
54: 55: 56: 57: 58: 59: 60: 61:
62: public function __construct($min = 0, $max = -1)
63: {
64: parent::__construct();
65:
66: Arguments::define(Boa::integer(), Boa::integer())
67: ->check($min, $max);
68:
69: if ($min < 0) {
70: throw new InvalidArgumentException(
71: 'The minimum length is expected to be >= 0.'
72: );
73: }
74:
75: if (($max != -1 && $max < $min) || $max < -1) {
76: throw new InvalidArgumentException('
77: The maximum length is expected to be: (== -1 || >= minimum) &&'
78: . ' >= -1.'
79: );
80: }
81:
82: $this->min = $min;
83: $this->max = $max;
84: }
85:
86: 87: 88: 89: 90: 91: 92: 93:
94: public function check($value, array $context = [])
95: {
96: $length = mb_strlen($value);
97:
98: return !Std::truthy(
99: ($this->min > $length),
100: ($this->max !== -1 && $this->max < $length)
101: );
102: }
103:
104: 105: 106: 107: 108:
109: public function toString()
110: {
111: if ($this->max !== -1) {
112: return vsprintf('{length: %d <= x <= %d}', [
113: $this->min,
114: $this->max,
115: ]);
116: }
117:
118: return vsprintf('{length: %d <= x}', [
119: $this->min,
120: ]);
121: }
122:
123: 124: 125: 126: 127:
128: public function getDescription()
129: {
130: if ($this->max !== -1) {
131: return vsprintf(
132: 'The value is expected to have a length between %d and %d'
133: . ' (%d <= x <= %d).',
134: [
135: $this->min,
136: $this->max,
137: $this->min,
138: $this->max,
139: ]
140: );
141: }
142:
143: return vsprintf(
144: 'The value is expected to have a length greater or equal to %d'
145: . ' (%d <= x).',
146: [
147: $this->min,
148: $this->min,
149: ]
150: );
151: }
152: }
153: