1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Author: Nil Portugués Calderó <[email protected]> |
4
|
|
|
* Date: 12/29/14 |
5
|
|
|
* Time: 8:57 PM |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace NilPortugues\Validator; |
12
|
|
|
|
13
|
|
|
use NilPortugues\Validator\Factory\ValidatorFactoryException; |
14
|
|
|
use NilPortugues\Validator\Factory\ValidatorRule; |
15
|
|
|
use NilPortugues\Validator\Factory\ValidatorType; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Class ValidatorFactory |
19
|
|
|
* @package NilPortugues\Validator |
20
|
|
|
*/ |
21
|
|
|
class ValidatorFactory |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* @param string $name |
25
|
|
|
* @param string $type |
26
|
|
|
* @param string[] $rules |
27
|
|
|
* |
28
|
|
|
* @throws Factory\ValidatorFactoryException |
29
|
|
|
* @return AbstractValidator |
30
|
|
|
*/ |
31
|
|
|
public static function create($name, $type, array $rules = []) |
32
|
|
|
{ |
33
|
|
|
if (false === ValidatorType::isSupported($type)) { |
34
|
|
|
throw new ValidatorFactoryException( |
35
|
|
|
\sprintf('The provided validator type \'%s\' is not supported.', $type) |
36
|
|
|
); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
|
40
|
|
|
$validator = self::createValidator($name, $type); |
41
|
|
|
|
42
|
|
|
return self::applyValidatorRules($validator, $rules); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @param string $name |
47
|
|
|
* @param string $type |
48
|
|
|
* |
49
|
|
|
* @return AbstractValidator |
50
|
|
|
*/ |
51
|
|
|
private static function createValidator($name, $type) |
52
|
|
|
{ |
53
|
|
|
return \call_user_func_array([Validator::create(), ValidatorType::getMethod($type)], [$name]); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param AbstractValidator $validator |
58
|
|
|
* @param string[] $rules |
59
|
|
|
* |
60
|
|
|
* @return AbstractValidator |
61
|
|
|
*/ |
62
|
|
|
private static function applyValidatorRules($validator, array &$rules) |
63
|
|
|
{ |
64
|
|
|
$validatorRule = ValidatorRule::getInstance(); |
65
|
|
|
foreach ($rules as $rule) { |
66
|
|
|
list($functionName, $arguments) = $validatorRule->parseRule($validator, $rule); |
67
|
|
|
$validator = \call_user_func_array([$validator, $functionName], $arguments); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
return $validator; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|