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