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

ClassNameValidator::validateParameters()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 4.128

Importance

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