Passed
Push — develop ( 5d2ce0...8a9894 )
by Daniel
04:55
created

ClassNameValidator::isClassSame()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
eloc 11
nc 6
nop 2
dl 0
loc 18
ccs 12
cts 12
cp 1
crap 7
rs 8.2222
c 0
b 0
f 0
1
<?php
2
3
namespace Silverback\ApiComponentBundle\Validator;
4
5
use ProxyManager\Proxy\LazyLoadingInterface;
6
use Symfony\Component\Validator\Exception\InvalidArgumentException;
7
8
class ClassNameValidator
9
{
10
    /**
11
     * @param string $className
12
     * @param $validClass
13
     * @return bool
14
     * @throws \ReflectionException
15
     */
16 8
    public static function isClassSame(string $className, $validClass): bool
17
    {
18 8
        if (!class_exists($className) && !interface_exists($className)) {
19 1
            throw new InvalidArgumentException(sprintf('The class/interface %s does not exist', $className));
20
        }
21 7
        if (!\is_object($validClass)) {
22 1
            throw new InvalidArgumentException(sprintf('The $validClass parameter %s is not an object', $validClass));
23
        }
24 6
        if (\get_class($validClass) === $className) {
25 3
            return true;
26
        }
27 5
        if (\in_array(LazyLoadingInterface::class, class_implements($validClass), true)) {
28 2
            $reflection = new \ReflectionClass($validClass);
29 2
            if ($reflection->isSubclassOf($className)) {
30 2
                return true;
31
            }
32
        }
33 4
        return ($validClass instanceof $className);
34
    }
35
36
    /**
37
     * @param string $className
38
     * @param iterable $validClasses
39
     * @return bool
40
     * @throws \Symfony\Component\Validator\Exception\InvalidArgumentException
41
     * @throws \ReflectionException
42
     */
43 2
    public static function validate(string $className, iterable $validClasses): bool
44
    {
45 2
        foreach ($validClasses as $validClass) {
46 2
            if (self::isClassSame($className, $validClass)) {
47 2
                return true;
48
            }
49
        }
50 1
        return false;
51
    }
52
}
53