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