forked from Respect/Validation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFactory.php
66 lines (52 loc) · 1.77 KB
/
Factory.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
<?php
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <[email protected]>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
namespace Respect\Validation;
use ReflectionClass;
use Respect\Validation\Exceptions\ComponentException;
class Factory
{
protected $rulePrefixes = ['Respect\\Validation\\Rules\\'];
public function getRulePrefixes()
{
return $this->rulePrefixes;
}
private function filterRulePrefix($rulePrefix)
{
$namespaceSeparator = '\\';
$rulePrefix = rtrim($rulePrefix, $namespaceSeparator);
return $rulePrefix.$namespaceSeparator;
}
public function appendRulePrefix($rulePrefix)
{
array_push($this->rulePrefixes, $this->filterRulePrefix($rulePrefix));
}
public function prependRulePrefix($rulePrefix)
{
array_unshift($this->rulePrefixes, $this->filterRulePrefix($rulePrefix));
}
public function rule($ruleName, array $arguments = [])
{
if ($ruleName instanceof Validatable) {
return $ruleName;
}
foreach ($this->getRulePrefixes() as $prefix) {
$className = $prefix.ucfirst($ruleName);
if (!class_exists($className)) {
continue;
}
$reflection = new ReflectionClass($className);
if (!$reflection->isSubclassOf('Respect\\Validation\\Validatable')) {
throw new ComponentException(sprintf('"%s" is not a valid respect rule', $className));
}
return $reflection->newInstanceArgs($arguments);
}
throw new ComponentException(sprintf('"%s" is not a valid rule name', $ruleName));
}
}