Completed
Pull Request — master (#27)
by Andres
02:13
created

Comfort::resolveValidator()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 3
eloc 7
c 1
b 0
f 1
nc 3
nop 1
dl 0
loc 13
rs 9.4285
1
<?php
2
namespace Comfort;
3
4
use Comfort\Validator\AbstractValidator;
5
use Comfort\Validator\AnyValidator;
6
use Comfort\Validator\ArrayValidator;
7
use Comfort\Validator\JsonValidator;
8
use Comfort\Validator\NumberValidator;
9
use Comfort\Validator\StringValidator;
10
11
/**
12
 * Class Comfort
13
 * @package Comfort
14
 * @method ArrayValidator array()
15
 * @method StringValidator string()
16
 * @method JsonValidator json()
17
 * @method NumberValidator number()
18
 * @method AnyValidator any()
19
 */
20
class Comfort
21
{
22
    /**
23
     * Mapped validators
24
     *
25
     * @var array
26
     */
27
    protected static $registeredValidators = [];
28
29
    /**
30
     * Returns validator for given data type
31
     *
32
     * @param $name
33
     * @param $arguments
34
     * @return ArrayValidator|JsonValidator|StringValidator|AnyValidator
35
     * @throws \RuntimeException
36
     */
37
    public function __call($name, $arguments)
38
    {
39
        $class = $this->resolveValidator($name);
40
        return new $class($this);
41
    }
42
43
    public static function registerValidator($name, $class)
44
    {
45
        if (!is_subclass_of($class, AbstractValidator::class)) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \Comfort\Validator\AbstractValidator::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
46
            throw new \RuntimeException($class . ' must extend ' . AbstractValidator::class);
47
        }
48
49
        self::$registeredValidators[$name] = $class;
50
    }
51
52
    /**
53
     * Return class name for validator
54
     *
55
     * @param $name
56
     * @return string
57
     */
58
    protected function resolveValidator($name)
59
    {
60
        if (array_key_exists($name, self::$registeredValidators)) {
61
            return self::$registeredValidators[$name];
62
        }
63
64
        $className = __NAMESPACE__ . '\\Validator\\' . ucfirst($name) . 'Validator';
65
        if (class_exists($className)) {
66
            return $className;
67
        }
68
69
        throw new \RuntimeException(sprintf('%s validator not found', $name));
70
    }
71
}
72