Passed
Push — develop ( 448334...a47dcf )
by nguereza
02:20
created

Validator::getLang()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
/**
4
 * Platine Validator
5
 *
6
 * Platine Validator is a simple, extensible validation library with support for filtering
7
 *
8
 * This content is released under the MIT License (MIT)
9
 *
10
 * Copyright (c) 2020 Platine Validator
11
 *
12
 * Permission is hereby granted, free of charge, to any person obtaining a copy
13
 * of this software and associated documentation files (the "Software"), to deal
14
 * in the Software without restriction, including without limitation the rights
15
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
 * copies of the Software, and to permit persons to whom the Software is
17
 * furnished to do so, subject to the following conditions:
18
 *
19
 * The above copyright notice and this permission notice shall be included in all
20
 * copies or substantial portions of the Software.
21
 *
22
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
 * SOFTWARE.
29
 */
30
31
/**
32
 *  @file Validator.php
33
 *
34
 *  The Validator class used to validate the input based on defined rules
35
 *
36
 *  @package    Platine\Validator
37
 *  @author Platine Developers Team
38
 *  @copyright  Copyright (c) 2020
39
 *  @license    http://opensource.org/licenses/MIT  MIT License
40
 *  @link   http://www.iacademy.cf
41
 *  @version 1.0.0
42
 *  @filesource
43
 */
44
45
declare(strict_types=1);
46
47
namespace Platine\Validator;
48
49
use Platine\Lang\Lang;
50
use Platine\Validator\Exception\ValidatorException;
51
52
/**
53
 * A Validator contains a set of validation rules and
54
 * associated metadata for ensuring that a given data set
55
 * is valid and returned correctly.
56
 */
57
class Validator
58
{
0 ignored issues
show
Coding Style introduced by
Opening brace must not be followed by a blank line
Loading history...
59
60
    /**
61
     * The data to validate
62
     * @var array<string, mixed>
63
     */
64
    protected array $data = [];
65
66
    /**
67
     * The field labels
68
     * @var array<string, string>
69
     */
70
    protected array $labels = [];
71
72
    /**
73
     * The filters to use to filter validation data
74
     * @var array<string, callable[]>
75
     */
76
    protected array $filters = [];
77
78
    /**
79
     * The validate rules
80
     * @var array<string, RuleInterface[]>
81
     */
82
    protected array $rules = [];
83
84
    /**
85
     * The validate errors
86
     * @var array<string, string>
87
     */
88
    protected array $errors = [];
89
90
    /**
91
     * The status of the validation
92
     * @var bool
93
     */
94
    protected bool $valid = false;
95
96
    /**
97
     * The validation language domain to use
98
     * @var string
99
     */
100
    protected string $langDomain;
101
102
    /**
103
     * The language to use
104
     * @var Lang
105
     */
106
    protected Lang $lang;
107
108
109
    /**
110
     * Create new instance
111
     * @param Lang $lang
112
     * @param string $langDomain
113
     */
114
    public function __construct(Lang $lang, string $langDomain = 'validators')
115
    {
116
        $this->lang = $lang;
117
        $this->langDomain = $langDomain;
118
119
        //Add the domain for the validator
120
        $this->lang->addDomain($langDomain);
121
122
        $this->reset();
123
    }
124
125
    /**
126
     * Return the language instance
127
     * @return Lang
128
     */
129
    public function getLang(): Lang
130
    {
131
        return $this->lang;
132
    }
133
134
    /**
135
     * Translation a single message
136
     * @param string $message
137
     * @param array<int, mixed>|mixed $args
138
     * @return string
139
     */
140
    public function translate(string $message, $args = []): string
141
    {
142
        if (!is_array($args)) {
143
            $args = array_slice(func_get_args(), 1);
144
        }
145
        
146
        return $this->lang->trd($message, $this->langDomain, $args);
147
    }
148
149
    /**
150
     * Reset the validation instance
151
     *
152
     * @return $this
153
     */
154
    public function reset(): self
155
    {
156
        $this->rules = [];
157
        $this->labels = [];
158
        $this->errors = [];
159
        $this->filters = [];
160
        $this->valid = false;
161
        $this->data = [];
162
163
        return $this;
164
    }
165
166
    /**
167
     * Set the validation data
168
     * @param array<string, mixed> $data the data to be validated
169
     *
170
     * @return $this
171
     */
172
    public function setData(array $data): self
173
    {
174
        $this->data = $data;
175
        return $this;
176
    }
177
178
    /**
179
     * Return the validation data
180
     *
181
     * @param string $field if is set will return only the data for this filed
182
     * @param mixed $default the default value to return if can not find field value
183
     * @return mixed
184
     */
185
    public function getData(?string $field = null, $default = null)
186
    {
187
        if ($field === null) {
188
            return $this->data;
189
        }
190
        return array_key_exists($field, $this->data) ? $this->data[$field] : $default;
191
    }
192
193
    /**
194
     * Return the validation status
195
     *
196
     * @return bool
197
     */
198
    public function isValid(): bool
199
    {
200
        return $this->valid;
201
    }
202
203
    /**
204
     * Set the Label for a given Field
205
     * @param string $field
206
     * @param string $label
207
     *
208
     * @return $this
209
     */
210
    public function setLabel(string $field, string $label): self
211
    {
212
        $this->labels[$field] = $label;
213
214
        return $this;
215
    }
216
217
    /**
218
     * Return the label for a given Field
219
     * @param string $field
220
     *
221
     * @return string the label if none is set will use the humanize value
222
     * of field
223
     */
224
    public function getLabel(string $field): string
225
    {
226
        return isset($this->labels[$field])
227
                ? $this->labels[$field]
228
                : $this->humanizeFieldName($field);
229
    }
230
231
    /**
232
     * Add a filter for the given field
233
     * @param string $field
234
     * @param callable $filter
235
     *
236
     * @return $this
237
     */
238
    public function addFilter(string $field, callable $filter): self
239
    {
240
        if (!isset($this->filters[$field])) {
241
            $this->filters[$field] = [];
242
        }
243
        $this->filters[$field][] = $filter;
244
245
        return $this;
246
    }
247
248
    /**
249
     * Add a list of filter for the given field
250
     * @param string $field
251
     * @param callable[] $filters
252
     *
253
     * @return $this
254
     */
255
    public function addFilters(string $field, array $filters): self
256
    {
257
        foreach ($filters as $filter) {
258
            if (!is_callable($filter)) {
259
                throw new ValidatorException('Filter must to be a valid callable');
260
            }
261
            $this->addFilter($field, $filter);
262
        }
263
264
        return $this;
265
    }
266
267
    /**
268
     * Add a rule for the given field
269
     * @param string $field
270
     * @param RuleInterface $rule
271
     *
272
     * @return $this
273
     */
274
    public function addRule(string $field, RuleInterface $rule): self
275
    {
276
        if (!isset($this->rules[$field])) {
277
            $this->rules[$field] = [];
278
        }
279
        if (!isset($this->labels[$field])) {
280
            $this->labels[$field] = $this->humanizeFieldName($field);
281
        }
282
        $this->rules[$field][] = $rule;
283
284
        return $this;
285
    }
286
287
    /**
288
     * Add a list of rules for the given field
289
     * @param string $field
290
     * @param RuleInterface[] $rules the array of RuleInterface
291
     *
292
     * @return $this
293
     */
294
    public function addRules(string $field, array $rules): self
295
    {
296
        foreach ($rules as $rule) {
297
            if (!$rule instanceof RuleInterface) {
298
                throw new ValidatorException(sprintf(
299
                    'Validation rule must implement [%s]!',
300
                    RuleInterface::class
301
                ));
302
            }
303
            $this->addRule($field, $rule);
304
        }
305
306
        return $this;
307
    }
308
309
    /**
310
     * Return all currently defined rules
311
     * @param string $field if set will return only for this field
312
     *
313
     * @return RuleInterface[]|array<string, RuleInterface[]>
314
     */
315
    public function getRules(?string $field = null): array
316
    {
317
        return $field !== null
318
                    ? (isset($this->rules[$field]) ? $this->rules[$field] : [])
319
                    : $this->rules;
320
    }
321
322
    /**
323
     * Validate the data
324
     * @param  array<string, mixed>  $data
325
     * @return bool       the validation status
326
     */
327
    public function validate(array $data = []): bool
328
    {
329
        if (!empty($data)) {
330
            $this->data = $data;
331
        }
332
        $this->applyFilters();
333
334
        $this->errors = $this->validateRules();
335
        $this->valid = empty($this->errors);
336
337
        return $this->valid;
338
    }
339
340
    /**
341
     * Return the validation errors
342
     * @return array<string, string> the validation errors
343
     *
344
     * @example array(
345
     *          'field1' => 'message 1',
346
     *          'field2' => 'message 2',
347
     * )
348
     */
349
    public function getErrors(): array
350
    {
351
        return $this->errors;
352
    }
353
354
    /**
355
     * Process to validation of fields rules
356
     * @return array<string, string> the validation errors
357
     */
358
    protected function validateRules(): array
359
    {
360
        if (empty($this->rules)) {
361
            return [];
362
        }
363
        $errors = [];
364
365
        foreach ($this->rules as $field => $rules) {
366
            list($result, $error) = $this->validateFieldRules($field, $rules);
367
            if ($result === false) {
368
                $errors[$field] = $error;
369
            }
370
        }
371
372
        return $errors;
373
    }
374
375
    /**
376
     * Validate the rules for the given field
377
     * @param  string $field
378
     * @param  RuleInterface[]  $rules the array of rules
379
     * @return array<mixed>     array(Status, error)
380
     */
381
    protected function validateFieldRules(string $field, array $rules): array
382
    {
383
        $value = isset($this->data[$field]) ? $this->data[$field] : null;
384
        foreach ($rules as $rule) {
385
            list($result, $error) = $this->validateRule($field, $value, $rule);
386
            if ($result === false) {
387
                return [false, $error];
388
            }
389
        }
390
391
        return [true, null];
392
    }
393
394
    /**
395
     * Validate single rule for the given field
396
     * @param  string $field
397
     * @param  mixed $value
398
     * @param  RuleInterface  $rule the rule instance to validate
399
     * @return array<mixed>     array(Status, error)
400
     */
401
    protected function validateRule(string $field, $value, RuleInterface $rule): array
402
    {
403
        $result = $rule->validate($field, $value, $this);
404
        if ($result) {
405
            return [true, null];
406
        }
407
        return [false, $rule->getErrorMessage($field, $value, $this)];
408
    }
409
410
    /**
411
     * Apply any defined filters to the validation data
412
     * @return array<string, mixed> the filtered data
413
     */
414
    protected function applyFilters(): array
415
    {
416
        if (empty($this->filters)) {
417
            return $this->data;
418
        }
419
420
        $data = $this->data;
421
422
        foreach ($this->filters as $field => $filters) {
423
            if (!isset($data[$field])) {
424
                continue;
425
            }
426
427
            $value = $data[$field];
428
            foreach ($filters as $filter) {
429
                $value = call_user_func($filter, $value);
430
            }
431
432
            $data[$field] = $value;
433
        }
434
        $this->data = $data;
435
436
        return $this->data;
437
    }
438
439
    /**
440
     * Humanize the given field
441
     * @param  string $field
442
     *
443
     * @return string
444
     */
445
    protected function humanizeFieldName(string $field): string
446
    {
447
        return str_replace(['-', '_'], ' ', $field);
448
    }
449
}
450