RangeValidator::validate()   C
last analyzed

Complexity

Conditions 7
Paths 32

Size

Total Lines 28
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
c 0
b 0
f 0
rs 6.7272
cc 7
eloc 16
nc 32
nop 1
1
<?php /** MicroRangeValidator */
2
3
namespace Micro\Validator;
4
5
use Micro\Form\IFormModel;
6
7
/**
8
 * RangeValidator class file.
9
 *
10
 * @author Oleg Lunegov <[email protected]>
11
 * @link https://github.com/linpax/microphp-framework
12
 * @copyright Copyright (c) 2013 Oleg Lunegov
13
 * @license https://github.com/linpax/microphp-framework/blob/master/LICENSE
14
 * @package Micro
15
 * @subpackage Validator
16
 * @version 1.0
17
 * @since 1.0
18
 */
19
class RangeValidator extends BaseValidator
20
{
21
    /**
22
     * @inheritdoc
23
     */
24
    public function validate(IFormModel $model)
25
    {
26
        if (empty($this->params['min'])) {
27
            $this->errors[] = 'Minimal value not declared to Range validator';
28
        }
29
        if (empty($this->params['max'])) {
30
            $this->errors[] = 'Maximal value not declared to Range validator';
31
        }
32
        $step = (!empty($this->params['step'])) ? $this->params['step'] : 1;
33
34
        $rang = range($this->params['min'], $this->params['max'], $step);
35
36
        foreach ($this->elements AS $element) {
37
            if (!$model->checkAttributeExists($element)) {
38
                $this->errors[] = 'Parameter '.$element.' not defined in class '.get_class($model);
39
40
                return false;
41
            }
42
            if (!in_array($model->$element, $rang, true)) {
43
                $this->errors[] = 'Parameter '.$element.' not find in rage '.
44
                    $this->params['min'].'..'.$this->params['max'];
45
46
                return false;
47
            }
48
        }
49
50
        return true;
51
    }
52
53
    /**
54
     * @inheritdoc
55
     */
56
    public function client(IFormModel $model)
57
    {
58
        return 'if (this.value < '.$this->params['min'].' || this.value > '.$this->params['max'].') {'.
59
            ' e.preventDefault(); this.focus(); alert(\'Value not find in range\'); }';
60
    }
61
}
62