Comfort   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 52
rs 10
c 0
b 0
f 0
wmc 6
lcom 1
cbo 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __call() 0 5 1
A registerValidator() 0 8 2
A resolveValidator() 0 13 3
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\DateValidator;
8
use Comfort\Validator\JsonValidator;
9
use Comfort\Validator\NumberValidator;
10
use Comfort\Validator\StringValidator;
11
12
/**
13
 * Class Comfort
14
 * @package Comfort
15
 * @method ArrayValidator array()
16
 * @method StringValidator string()
17
 * @method JsonValidator json()
18
 * @method NumberValidator number()
19
 * @method AnyValidator any()
20
 * @method DateValidator date()
21
 */
22
class Comfort
23
{
24
    /**
25
     * Mapped validators
26
     *
27
     * @var array
28
     */
29
    protected static $registeredValidators = [];
30
31
    /**
32
     * Returns validator for given data type
33
     *
34
     * @param $name
35
     * @param $arguments
36
     * @return ArrayValidator|JsonValidator|StringValidator|AnyValidator|DateValidator
37
     * @throws \RuntimeException
38
     */
39
    public function __call($name, $arguments)
40
    {
41
        $class = $this->resolveValidator($name);
42
        return new $class($this);
43
    }
44
45
    public static function registerValidator($name, $class)
46
    {
47
        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...
48
            throw new \RuntimeException($class . ' must extend ' . AbstractValidator::class);
49
        }
50
51
        self::$registeredValidators[$name] = $class;
52
    }
53
54
    /**
55
     * Return class name for validator
56
     *
57
     * @param $name
58
     * @return string
59
     */
60
    protected function resolveValidator($name)
61
    {
62
        if (array_key_exists($name, self::$registeredValidators)) {
63
            return self::$registeredValidators[$name];
64
        }
65
66
        $className = __NAMESPACE__ . '\\Validator\\' . ucfirst($name) . 'Validator';
67
        if (class_exists($className)) {
68
            return $className;
69
        }
70
71
        throw new \RuntimeException(sprintf('%s validator not found', $name));
72
    }
73
}
74