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

ClassNameValidator::isClassSameLazy()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 2
rs 10
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