Passed
Push — feature/unit-tests ( 099642...9ae529 )
by Daniel
05:21
created

ClassNameValidator   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 95.24%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 45
ccs 20
cts 21
cp 0.9524
rs 10
wmc 12

4 Methods

Rating   Name   Duplication   Size   Complexity  
A isClassSame() 0 8 3
A validateParameters() 0 7 4
A validate() 0 9 3
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
        self::validateParameters($className, $validClass);
42 4
        if (\get_class($validClass) === $className) {
43 2
            return true;
44
        }
45
46 3
        return self::isClassSameLazy($className, $validClass) ?: ($validClass instanceof $className);
47
    }
48
49 6
    private static function validateParameters(string $className, $validClass): void
50
    {
51 6
        if (!class_exists($className) && !interface_exists($className)) {
52 2
            throw new InvalidArgumentException(sprintf('The class/interface %s does not exist', $className));
53
        }
54 4
        if (!\is_object($validClass)) {
55
            throw new InvalidArgumentException(sprintf('The $validClass parameter %s is not an object', $validClass));
56
        }
57 4
    }
58
59
    /** @throws ReflectionException */
60 3
    private static function isClassSameLazy(string $className, $validClass): bool
61
    {
62 3
        if (\in_array(LazyLoadingInterface::class, class_implements($validClass), true)) {
63 1
            $reflection = new ReflectionClass($validClass);
64
65 1
            return $reflection->isSubclassOf($className);
66
        }
67
68 3
        return false;
69
    }
70
}
71