Passed
Push — master ( 662aa8...af8ac0 )
by Tõnis
01:55
created

VariableNameValidator::validateAttribute()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 5
nc 4
nop 2
1
<?php
2
3
namespace dameter\abstracts\validators;
4
5
use yii\validators\StringValidator;
6
7
8
/**
9
 * Class VariableNameValidator
10
 * @author Tõnis Ormisson <[email protected]>
11
 */
12
class VariableNameValidator extends StringValidator
13
{
14
    public $max = 64;
15
16
    /** @var string $containsSpacesMsg A message if the value contains spaces */
17
    public $containsSpacesMsg;
18
19
    /** @var string $invalidFirstLetterMsg A message if invalid first letter */
20
    public $invalidFirstLetterMsg;
21
    /**
22
     * {@inheritdoc}
23
     */
24
    public function init()
25
    {
26
        parent::init();
27
        $this->containsSpacesMsg = \Yii::t('dmabstract', "{attribute} must not contain spaces!");
28
        $this->containsSpacesMsg = \Yii::t('dmabstract', "The first character of {attribute} must be a letter!");
29
    }
30
31
32
    /**
33
     * {@inheritdoc}
34
     */
35
    public function validateAttribute($model, $attribute)
36
    {
37
        parent::validateAttribute($model, $attribute);
38
39
        if (strpos($model->{$attribute}, ' ') !== false) {
40
            $this->addError($model, $attribute, $this->containsSpacesMsg);
41
        }
42
43
        if (!ctype_alpha($model->{$attribute}[0])) {
44
            $this->addError($model, $attribute, $this->invalidFirstLetterMsg);
45
        }
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    protected function validateValue($value)
52
    {
53
54
        $validation = parent::validateValue($value);
55
56
        if (!is_null($validation)) {
57
            return $validation;
58
        }
59
60
        if (strpos($value, ' ') !== false) {
61
            return [$this->containsSpacesMsg, []];
62
        }
63
        if (!ctype_alpha($value[0])) {
64
            return [$this->invalidFirstLetterMsg, []];
65
        }
66
        return null;
67
    }
68
69
70
}