Passed
Push — feature/unit-tests ( a1039c...d9a81b )
by Daniel
09:12 queued 04:33
created

ClassNameValidator   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 10
eloc 14
c 2
b 0
f 0
dl 0
loc 38
ccs 16
cts 16
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 9 3
A isClassSame() 0 11 5
A isClassSameLazy() 0 9 2
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Component 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\ApiComponentBundle\Validator;
15
16
use ProxyManager\Proxy\LazyLoadingInterface;
17
use ReflectionClass;
18
use ReflectionException;
19
use Symfony\Component\Validator\Exception\InvalidArgumentException;
20
21
/**
22
 * @author Daniel West <[email protected]>
23
 */
24
class ClassNameValidator
25
{
26
    /** @throws ReflectionException */
27 4
    public static function validate(string $className, iterable $validClasses): bool
28
    {
29 4
        foreach ($validClasses as $validClass) {
30 4
            if (self::isClassSame($className, $validClass)) {
31 2
                return true;
32
            }
33
        }
34
35 1
        return false;
36
    }
37
38
    /** @throws ReflectionException */
39 6
    public static function isClassSame(string $className, object $validClass): bool
40
    {
41 6
        if (!class_exists($className) && !interface_exists($className)) {
42 2
            throw new InvalidArgumentException(sprintf('The class/interface %s does not exist', $className));
43
        }
44
45 4
        if (\get_class($validClass) === $className) {
46 2
            return true;
47
        }
48
49 3
        return self::isClassSameLazy($className, $validClass) ?: ($validClass instanceof $className);
50
    }
51
52
    /** @throws ReflectionException */
53 3
    private static function isClassSameLazy(string $className, $validClass): bool
54
    {
55 3
        if (\in_array(LazyLoadingInterface::class, class_implements($validClass), true)) {
56 1
            $reflection = new ReflectionClass($validClass);
57
58 1
            return $reflection->isSubclassOf($className);
59
        }
60
61 3
        return false;
62
    }
63
}
64