respect-validation/library/Factory.php

59 lines
1.5 KiB
PHP
Raw Normal View History

<?php
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* 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
{
2015-10-18 03:44:47 +02:00
protected $rulePrefixes = ['Respect\\Validation\\Rules\\'];
public function getRulePrefixes()
{
return $this->rulePrefixes;
}
public function appendRulePrefix($rulePrefix)
{
array_push($this->rulePrefixes, $rulePrefix);
}
public function prependRulePrefix($rulePrefix)
{
array_unshift($this->rulePrefixes, $rulePrefix);
}
2015-10-18 03:44:47 +02:00
public function rule($ruleName, array $arguments = [])
{
if ($ruleName instanceof Validatable) {
return $ruleName;
}
foreach ($this->getRulePrefixes() as $prefix) {
$className = $prefix.ucfirst($ruleName);
2015-06-08 16:47:14 +02:00
if (!class_exists($className)) {
continue;
}
$reflection = new ReflectionClass($className);
2015-06-08 16:47:14 +02:00
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));
}
}