-
Notifications
You must be signed in to change notification settings - Fork 1
/
WordValidator.php
420 lines (379 loc) · 10.7 KB
/
WordValidator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
<?php
/**
*
* WordValidator class file.
*
* @author Anton Yakushin <[email protected]>
* @author Herbert Maschke <[email protected]> (Port to yii2)
* @version 0.1
* @link https://github.com/thyseus/yii2-word-validator
* @license GPL
*/
/**
* WordValidator validates that the attribute value has a specific words count
* and checks this value against a whitelist and blacklist.
*
* This extension has been inspired from
* @author Anton Yakushin <[email protected]>
* https://github.com/antonCPU/word-validator
* and can be seen as a port to Yii 2.
*
* The error messages could be specified in {@link $messages}.
* All messages may contain placeholders {attribute} and {length}, where
* {length} is a word count of the validated value.
* Also each validation rule adds a correspond value to the error message.
* For the max rule the message could be:
* <ul>
* <li>{attribute} is too long (maximum is {max} words, but now it's {length})
* </ul>
* The {@link $message} is also supported. This message is used for all
* cases when a specific message in {@link $messages} was not provided.
*
* Usage example.
* Check if a "body" attribute has from 2 to 5 words count, contains
* either the word "please" or "test" and does not contain a word "restricted"
* and "email.*" expression. Also the default message for "max" rule is overridden.
* <code>
* use app\components\WordValidator;
*
* public function rules() {
* return [
* [['message'], WordValidator::className(),
* 'min' => 2,
* 'max' => 5,
* 'whitelist' => array('please', 'test'),
* 'blacklist' => array('restricted', 'email.*'), //could be a regular expression
* 'messages' => array(
* 'max' => '{attribute} is too long (maximum is {max} words, but now it\'s {length})'
* ),
* ];
* ];
}
* </code>
*/
namespace thyseus\validators;
use Yii;
use yii\validators\Validator;
use yii\helpers\Json;
class WordValidator extends Validator
{
/**
* @var int maximum number of words.
*/
public $max;
/**
* @var int minimum number of words.
*/
public $min;
/**
* @var int only this number of words.
*/
public $exact;
/**
* List of words/expressions that should not be inside the value.
* Regular expressions are allowed.
* @var array
*/
public $blacklist;
/**
* At least one of these words/expressions should be inside the value.
* Regular expressions are allowed.
* @var array
*/
public $whitelist;
/**
* List of error messages.
* A key is an available validatation rule and a value is a message with
* placeholders. All messages support {attribute} and {length} placeholders.
* Also each method adds a correspond value to a message.
* @var array
* @see WordValidator::getDefaultMessages()
*/
public $messages;
/**
* Used for combining blacklist and whitelist values for an error message.
* @var string
*/
public $clue = ', ';
/**
* Filter for data that is applied before any of rules.
* Accepts data as a first argument.
* @var mixed a valid php callback.
* @since 1.1
*/
public $filter;
/**
* Filter for client side value.
* @var string javascript callback.
* @since 1.1
*/
public $filterClient;
private $_source;
private $_length;
private $_object;
private $_attribute;
/**
* Validates a single attribute.
* @param Model $object the data object being validated
* @param string $attribute the name of the attribute to be validated.
*/
public function validateAttribute($object, $attribute)
{
$this->_source = null;
$this->_length = null;
$this->_object = $object;
$this->_attribute = $attribute;
foreach ($this->getRules() as $rule) {
$this->checkRule($rule);
}
}
/**
* Gets a list of available rules.
* @return array
*/
protected function getRules()
{
return array('max', 'min', 'exact', 'blacklist', 'whitelist');
}
/**
* Gets a number of words in the value.
* @return int
* @since 1.1 is public
*/
public function getLength()
{
if (null === $this->_length) {
$this->_length = str_word_count($this->getSource());
}
return $this->_length;
}
/**
* Gets the value.
* @return string
*/
protected function getSource()
{
if (null === $this->_source) {
$this->_source = $this->_object->{$this->_attribute};
if ($this->filter && is_callable($this->filter)) {
$this->_source = call_user_func($this->filter, $this->_source);
}
}
return $this->_source;
}
/**
* Checks rule if needed and adds an error message.
* @param string $rule
*/
protected function checkRule($rule)
{
if ((null === $this->$rule) || !$this->getLength()) {
return;
}
if (!$this->{'check' . ucfirst($rule)}()) {
$this->addErrorMessage($rule);
}
}
/**
* @return bool
*/
protected function checkMax()
{
return $this->getLength() <= $this->max;
}
/**
* @return bool
*/
protected function checkMin()
{
return $this->getLength() >= $this->min;
}
/**
* @return bool
*/
protected function checkExact()
{
return $this->getLength() == $this->exact;
}
/**
* @return bool
*/
protected function checkBlacklist()
{
return !$this->checkList($this->blacklist);
}
/**
* @return bool
*/
protected function checkWhitelist()
{
return $this->checkList($this->whitelist);
}
/**
* @param array $list
* @return bool
*/
protected function checkList($list)
{
$pattern = '/\b((' . implode(')|(', $list) . '))\b/i';
return preg_match($pattern, $this->getSource());
}
/**
* @param string $rule
*/
protected function addErrorMessage($rule)
{
$params[$rule] = $this->formParam($this->$rule);
$params['length'] = $this->getLength();
$this->addError($this->_object, $this->_attribute,
Yii::t('app', $this->getMessage($rule), $params));
}
/**
* Forms a value compatible with one parameter for WordValidator::addError().
* @param mixed $value
* @return string
*/
protected function formParam($value)
{
return is_array($value) ? implode($this->clue, $value) : $value;
}
/**
* Gets an error message.
* @param string $rule
* @return string
*/
protected function getMessage($rule)
{
if (isset($this->messages[$rule])) {
return $this->messages[$rule];
} elseif (isset($this->message)) {
return $this->message;
}
$messages = $this->getDefaultMessages();
return Yii::t('app', $messages[$rule], [
'attribute' => $this->_attribute,
'min' => $this->min,
'max' => $this->max,
'exact' => $this->exact,
'blacklist' => $this->blacklist ? implode(',', $this->blacklist) : [],
]);
}
/**
* Gets a list of default error messages.
* @return array
*/
protected function getDefaultMessages()
{
return array(
'max' => Yii::t('app', '{attribute} is too long (maximum is {max} words).'),
'min' => Yii::t('app', '{attribute} is too short (minimum is {min} words).'),
'exact' => Yii::t('app', '{attribute} is of the wrong length (should be {exact} words).'),
'blacklist' => Yii::t('app', '{attribute} should not contain words ({blacklist}).'),
'whitelist' => Yii::t('app', '{attribute} should contain at least one of the words ({whitelist}).')
);
}
/**
* Returns the JavaScript needed for performing client-side validation.
* @param CModel $object the data object being validated
* @param string $attribute the name of the attribute to be validated.
* @return string the client-side validation script.
* @see CActiveForm::enableClientValidation
*/
public function clientValidateAttribute($object, $attribute, $view)
{
$this->_object = $object;
$this->_attribute = $attribute;
$validation = 'var wordCount=' . $this->calcClientLength() . ';';
foreach ($this->getRules() as $rule) {
$validation .= $this->checkClientRule($rule);
}
return $validation;
}
/**
* @param string $rule
* @return string
*/
protected function getClientMessage($rule)
{
$params[$rule] = $this->formParam($this->$rule);
return Yii::t('app', $this->getMessage($rule), $params);
}
/**
* Forms a block for one validation rule.
* @param string $rule
* @return string
*/
protected function checkClientRule($rule)
{
if (!$this->$rule) {
return;
}
$method = 'checkClient' . ucfirst($rule);
return ' if (!(' . $this->{$method}() . ') && wordCount)
{
messages.push(' . JSON::encode($this->getClientMessage($rule))
. '.replace("{length}", wordCount));
}; ';
}
/**
* @return string
*/
protected function checkClientMax()
{
return 'wordCount <=' . $this->max;
}
/**
* @return string
*/
protected function checkClientMin()
{
return 'wordCount >=' . $this->min;
}
/**
* @return string
*/
protected function checkClientExact()
{
return 'wordCount ==' . $this->exact;
}
/**
* @return string
*/
protected function checkClientBlackList()
{
return '!' . $this->checkClientList($this->blacklist);
}
/**
* @return string
*/
protected function checkClientWhiteList()
{
return $this->checkClientList($this->whitelist);
}
/**
* @param array
* @return string
*/
protected function checkClientList($list)
{
return $this->getClientSource() . '.match(/\b((' . implode(')|(', $list) . '))\b/i)';
}
/**
* Calculates number of words.
* @return string
*/
protected function calcClientLength()
{
return '(wordCount = jQuery.trim(' . $this->getClientSource() . '.replace(/\s+/g," ")))
? wordCount.split(" ").length : 0';
}
/**
* Gets the value.
* @return string
* @since 1.1
*/
protected function getClientSource()
{
return $this->filterClient ? $this->filterClient . '(value)' : 'value';
}
}