Passed
Push — bizley-patch-2 ( fe558b )
by Paweł
19:34
created

TrimValidator::clientValidateAttribute()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
c 1
b 0
f 0
nc 2
nop 3
dl 0
loc 10
rs 10
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\validators;
9
10
/**
11
 * This class converts the attribute value(s) to string(s) and strip characters.
12
 *
13
 * @since 2.0.46
14
 */
15
class TrimValidator extends Validator
16
{
17
    /**
18
     * @var string The list of characters to strip, with `..` can specify a range of characters.
19
     * For example, set '\/ ' to normalize path or namespace.
20
     */
21
    public $chars;
22
    /**
23
     * @var bool Whether the filter should be skipped if an array input is given.
24
     * If true and an array input is given, the filter will not be applied.
25
     */
26
    public $skipOnArray = false;
27
    /**
28
     * @inheritDoc
29
     */
30
    public $skipOnEmpty = false;
31
32
    /**
33
     * @inheritDoc
34
     */
35
    public function validateAttribute($model, $attribute)
36
    {
37
        $value = $model->$attribute;
38
        if (!$this->skipOnArray || !is_array($value)) {
39
            $model->$attribute = is_array($value)
40
                ? array_map([$this, 'trimValue'], $value)
41
                : $this->trimValue($value);
42
        }
43
    }
44
45
    /**
46
     * Converts given value to string and strips declared characters.
47
     *
48
     * @param mixed $value the value to strip
49
     * @return string
50
     */
51
    protected function trimValue($value)
52
    {
53
        return $this->isEmpty($value) ? '' : trim((string) $value, $this->chars ?: " \n\r\t\v\x00");
54
    }
55
56
    /**
57
     * @inheritDoc
58
     */
59
    public function clientValidateAttribute($model, $attribute, $view)
60
    {
61
        if ($this->skipOnArray && is_array($model->$attribute)) {
62
            return null;
63
        }
64
65
        ValidationAsset::register($view);
66
        $options = $this->getClientOptions($model, $attribute);
67
68
        return 'value = yii.validation.trim($form, attribute, ' . json_encode($options) . ', value);';
69
    }
70
71
    /**
72
     * @inheritDoc
73
     */
74
    public function getClientOptions($model, $attribute)
75
    {
76
        return [
77
            'skipOnArray' => (bool) $this->skipOnArray,
78
            'skipOnEmpty' => (bool) $this->skipOnEmpty,
79
            'chars' => $this->chars ?: false,
80
        ];
81
    }
82
}
83