ClassNameValidator::validate()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 3
nop 2
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Components Bundle Project
5
 *
6
 * (c) Daniel West <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Silverback\ApiComponentsBundle\Validator;
15
16
use ProxyManager\Proxy\LazyLoadingInterface;
17
use Silverback\ApiComponentsBundle\Exception\InvalidArgumentException;
18
19
/**
20
 * @author Daniel West <[email protected]>
21
 */
22
class ClassNameValidator
23
{
24
    /** @throws \ReflectionException */
25 4
    public static function validate(string $className, iterable $validClasses): bool
26
    {
27 4
        foreach ($validClasses as $validClass) {
28 4
            if (self::isClassSame($className, $validClass)) {
29 2
                return true;
30
            }
31
        }
32
33 1
        return false;
34
    }
35
36
    /** @throws \ReflectionException */
37 6
    public static function isClassSame(string $className, object $validClass): bool
38
    {
39 6
        if (!class_exists($className) && !interface_exists($className)) {
40 2
            throw new InvalidArgumentException(sprintf('The class/interface %s does not exist', $className));
41
        }
42
43 4
        if ($validClass::class === $className) {
44 2
            return true;
45
        }
46
47 3
        return self::isClassSameLazy($className, $validClass) ?: ($validClass instanceof $className);
48
    }
49
50
    /** @throws \ReflectionException */
51 3
    private static function isClassSameLazy(string $className, $validClass): bool
52
    {
53 3
        if (\in_array(LazyLoadingInterface::class, class_implements($validClass), true)) {
54 1
            $reflection = new \ReflectionClass($validClass);
55
56 1
            return $reflection->isSubclassOf($className);
57
        }
58
59 3
        return false;
60
    }
61
}
62