This repository has been archived by the owner on Jan 31, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 136
/
AbstractValidator.php
574 lines (511 loc) · 16.3 KB
/
AbstractValidator.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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator;
use Traversable;
use Zend\Stdlib\ArrayUtils;
abstract class AbstractValidator implements
Translator\TranslatorAwareInterface,
ValidatorInterface
{
/**
* The value to be validated
*
* @var mixed
*/
protected $value;
/**
* Default translation object for all validate objects
* @var Translator\TranslatorInterface
*/
protected static $defaultTranslator;
/**
* Default text domain to be used with translator
* @var string
*/
protected static $defaultTranslatorTextDomain = 'default';
/**
* Limits the maximum returned length of an error message
*
* @var int
*/
protected static $messageLength = -1;
protected $abstractOptions = [
'messages' => [], // Array of validation failure messages
'messageTemplates' => [], // Array of validation failure message templates
'messageVariables' => [], // Array of additional variables available for validation failure messages
'translator' => null, // Translation object to used -> Translator\TranslatorInterface
'translatorTextDomain' => null, // Translation text domain
'translatorEnabled' => true, // Is translation enabled?
'valueObscured' => false, // Flag indicating whether or not value should be obfuscated
// in error messages
];
/**
* Abstract constructor for all validators
* A validator should accept following parameters:
* - nothing f.e. Validator()
* - one or multiple scalar values f.e. Validator($first, $second, $third)
* - an array f.e. Validator(array($first => 'first', $second => 'second', $third => 'third'))
* - an instance of Traversable f.e. Validator($config_instance)
*
* @param array|Traversable $options
*/
public function __construct($options = null)
{
// The abstract constructor allows no scalar values
if ($options instanceof Traversable) {
$options = ArrayUtils::iteratorToArray($options);
}
if (isset($this->messageTemplates)) {
$this->abstractOptions['messageTemplates'] = $this->messageTemplates;
}
if (isset($this->messageVariables)) {
$this->abstractOptions['messageVariables'] = $this->messageVariables;
}
if (is_array($options)) {
$this->setOptions($options);
}
}
/**
* Returns an option
*
* @param string $option Option to be returned
* @return mixed Returned option
* @throws Exception\InvalidArgumentException
*/
public function getOption($option)
{
if (array_key_exists($option, $this->abstractOptions)) {
return $this->abstractOptions[$option];
}
if (isset($this->options) && array_key_exists($option, $this->options)) {
return $this->options[$option];
}
throw new Exception\InvalidArgumentException("Invalid option '$option'");
}
/**
* Returns all available options
*
* @return array Array with all available options
*/
public function getOptions()
{
$result = $this->abstractOptions;
if (isset($this->options)) {
$result += $this->options;
}
return $result;
}
/**
* Sets one or multiple options
*
* @param array|Traversable $options Options to set
* @throws Exception\InvalidArgumentException If $options is not an array or Traversable
* @return AbstractValidator Provides fluid interface
*/
public function setOptions($options = [])
{
if (! is_array($options) && ! $options instanceof Traversable) {
throw new Exception\InvalidArgumentException(__METHOD__ . ' expects an array or Traversable');
}
foreach ($options as $name => $option) {
$fname = 'set' . ucfirst($name);
$fname2 = 'is' . ucfirst($name);
if (($name !== 'setOptions') && method_exists($this, $name)) {
$this->{$name}($option);
} elseif (($fname !== 'setOptions') && method_exists($this, $fname)) {
$this->{$fname}($option);
} elseif (method_exists($this, $fname2)) {
$this->{$fname2}($option);
} elseif (isset($this->options)) {
$this->options[$name] = $option;
} else {
$this->abstractOptions[$name] = $option;
}
}
return $this;
}
/**
* Returns array of validation failure messages
*
* @return array
*/
public function getMessages()
{
return array_unique($this->abstractOptions['messages'], SORT_REGULAR);
}
/**
* Invoke as command
*
* @param mixed $value
* @return bool
*/
public function __invoke($value)
{
return $this->isValid($value);
}
/**
* Returns an array of the names of variables that are used in constructing validation failure messages
*
* @return array
*/
public function getMessageVariables()
{
return array_keys($this->abstractOptions['messageVariables']);
}
/**
* Returns the message templates from the validator
*
* @return array
*/
public function getMessageTemplates()
{
return $this->abstractOptions['messageTemplates'];
}
/**
* Sets the validation failure message template for a particular key
*
* @param string $messageString
* @param string $messageKey OPTIONAL
* @return AbstractValidator Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function setMessage($messageString, $messageKey = null)
{
if ($messageKey === null) {
$keys = array_keys($this->abstractOptions['messageTemplates']);
foreach ($keys as $key) {
$this->setMessage($messageString, $key);
}
return $this;
}
if (! isset($this->abstractOptions['messageTemplates'][$messageKey])) {
throw new Exception\InvalidArgumentException("No message template exists for key '$messageKey'");
}
$this->abstractOptions['messageTemplates'][$messageKey] = $messageString;
return $this;
}
/**
* Sets validation failure message templates given as an array, where the array keys are the message keys,
* and the array values are the message template strings.
*
* @param array $messages
* @return AbstractValidator
*/
public function setMessages(array $messages)
{
foreach ($messages as $key => $message) {
$this->setMessage($message, $key);
}
return $this;
}
/**
* Magic function returns the value of the requested property, if and only if it is the value or a
* message variable.
*
* @param string $property
* @return mixed
* @throws Exception\InvalidArgumentException
*/
public function __get($property)
{
if ($property == 'value') {
return $this->value;
}
if (array_key_exists($property, $this->abstractOptions['messageVariables'])) {
$result = $this->abstractOptions['messageVariables'][$property];
if (is_array($result)) {
return $this->{key($result)}[current($result)];
}
return $this->{$result};
}
if (isset($this->messageVariables) && array_key_exists($property, $this->messageVariables)) {
$result = $this->{$this->messageVariables[$property]};
if (is_array($result)) {
return $this->{key($result)}[current($result)];
}
return $this->{$result};
}
throw new Exception\InvalidArgumentException("No property exists by the name '$property'");
}
/**
* Constructs and returns a validation failure message with the given message key and value.
*
* Returns null if and only if $messageKey does not correspond to an existing template.
*
* If a translator is available and a translation exists for $messageKey,
* the translation will be used.
*
* @param string $messageKey
* @param string|array|object $value
* @return string
*/
protected function createMessage($messageKey, $value)
{
if (! isset($this->abstractOptions['messageTemplates'][$messageKey])) {
return;
}
$message = $this->abstractOptions['messageTemplates'][$messageKey];
$message = $this->translateMessage($messageKey, $message);
if (is_object($value) &&
! in_array('__toString', get_class_methods($value))
) {
$value = get_class($value) . ' object';
} elseif (is_array($value)) {
$value = var_export($value, 1);
} else {
$value = (string) $value;
}
if ($this->isValueObscured()) {
$value = str_repeat('*', strlen($value));
}
$message = str_replace('%value%', (string) $value, $message);
foreach ($this->abstractOptions['messageVariables'] as $ident => $property) {
if (is_array($property)) {
$value = $this->{key($property)}[current($property)];
if (is_array($value)) {
$value = '[' . implode(', ', $value) . ']';
}
} else {
$value = $this->$property;
}
$message = str_replace("%$ident%", (string) $value, $message);
}
$length = self::getMessageLength();
if (($length > -1) && (strlen($message) > $length)) {
$message = substr($message, 0, ($length - 3)) . '...';
}
return $message;
}
/**
* @param string $messageKey
* @param string $value OPTIONAL
* @return void
*/
protected function error($messageKey, $value = null)
{
if ($messageKey === null) {
$keys = array_keys($this->abstractOptions['messageTemplates']);
$messageKey = current($keys);
}
if ($value === null) {
$value = $this->value;
}
$this->abstractOptions['messages'][$messageKey] = $this->createMessage($messageKey, $value);
}
/**
* Returns the validation value
*
* @return mixed Value to be validated
*/
protected function getValue()
{
return $this->value;
}
/**
* Sets the value to be validated and clears the messages and errors arrays
*
* @param mixed $value
* @return void
*/
protected function setValue($value)
{
$this->value = $value;
$this->abstractOptions['messages'] = [];
}
/**
* Set flag indicating whether or not value should be obfuscated in messages
*
* @param bool $flag
* @return AbstractValidator
*/
public function setValueObscured($flag)
{
$this->abstractOptions['valueObscured'] = (bool) $flag;
return $this;
}
/**
* Retrieve flag indicating whether or not value should be obfuscated in
* messages
*
* @return bool
*/
public function isValueObscured()
{
return $this->abstractOptions['valueObscured'];
}
/**
* Set translation object
*
* @param Translator\TranslatorInterface|null $translator
* @param string $textDomain (optional)
* @return AbstractValidator
* @throws Exception\InvalidArgumentException
*/
public function setTranslator(Translator\TranslatorInterface $translator = null, $textDomain = null)
{
$this->abstractOptions['translator'] = $translator;
if (null !== $textDomain) {
$this->setTranslatorTextDomain($textDomain);
}
return $this;
}
/**
* Return translation object
*
* @return Translator\TranslatorInterface|null
*/
public function getTranslator()
{
if (! $this->isTranslatorEnabled()) {
return;
}
if (null === $this->abstractOptions['translator']) {
$this->abstractOptions['translator'] = self::getDefaultTranslator();
}
return $this->abstractOptions['translator'];
}
/**
* Does this validator have its own specific translator?
*
* @return bool
*/
public function hasTranslator()
{
return (bool) $this->abstractOptions['translator'];
}
/**
* Set translation text domain
*
* @param string $textDomain
* @return AbstractValidator
*/
public function setTranslatorTextDomain($textDomain = 'default')
{
$this->abstractOptions['translatorTextDomain'] = $textDomain;
return $this;
}
/**
* Return the translation text domain
*
* @return string
*/
public function getTranslatorTextDomain()
{
if (null === $this->abstractOptions['translatorTextDomain']) {
$this->abstractOptions['translatorTextDomain'] =
self::getDefaultTranslatorTextDomain();
}
return $this->abstractOptions['translatorTextDomain'];
}
/**
* Set default translation object for all validate objects
*
* @param Translator\TranslatorInterface|null $translator
* @param string $textDomain (optional)
* @return void
* @throws Exception\InvalidArgumentException
*/
public static function setDefaultTranslator(Translator\TranslatorInterface $translator = null, $textDomain = null)
{
static::$defaultTranslator = $translator;
if (null !== $textDomain) {
self::setDefaultTranslatorTextDomain($textDomain);
}
}
/**
* Get default translation object for all validate objects
*
* @return Translator\TranslatorInterface|null
*/
public static function getDefaultTranslator()
{
return static::$defaultTranslator;
}
/**
* Is there a default translation object set?
*
* @return bool
*/
public static function hasDefaultTranslator()
{
return (bool) static::$defaultTranslator;
}
/**
* Set default translation text domain for all validate objects
*
* @param string $textDomain
* @return void
*/
public static function setDefaultTranslatorTextDomain($textDomain = 'default')
{
static::$defaultTranslatorTextDomain = $textDomain;
}
/**
* Get default translation text domain for all validate objects
*
* @return string
*/
public static function getDefaultTranslatorTextDomain()
{
return static::$defaultTranslatorTextDomain;
}
/**
* Indicate whether or not translation should be enabled
*
* @param bool $flag
* @return AbstractValidator
*/
public function setTranslatorEnabled($flag = true)
{
$this->abstractOptions['translatorEnabled'] = (bool) $flag;
return $this;
}
/**
* Is translation enabled?
*
* @return bool
*/
public function isTranslatorEnabled()
{
return $this->abstractOptions['translatorEnabled'];
}
/**
* Returns the maximum allowed message length
*
* @return int
*/
public static function getMessageLength()
{
return static::$messageLength;
}
/**
* Sets the maximum allowed message length
*
* @param int $length
*/
public static function setMessageLength($length = -1)
{
static::$messageLength = $length;
}
/**
* Translate a validation message
*
* @param string $messageKey
* @param string $message
* @return string
*/
protected function translateMessage($messageKey, $message)
{
$translator = $this->getTranslator();
if (! $translator) {
return $message;
}
return $translator->translate($message, $this->getTranslatorTextDomain());
}
}