|
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
|
1 |
|
public static function validate(string $className, iterable $validClasses): bool |
|
28
|
|
|
{ |
|
29
|
1 |
|
foreach ($validClasses as $validClass) { |
|
30
|
1 |
|
if (self::isClassSame($className, $validClass)) { |
|
31
|
1 |
|
return true; |
|
32
|
|
|
} |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
return false; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** @throws ReflectionException */ |
|
39
|
3 |
|
public static function isClassSame(string $className, object $validClass): bool |
|
40
|
|
|
{ |
|
41
|
3 |
|
self::validateParameters($className, $validClass); |
|
42
|
2 |
|
if (\get_class($validClass) === $className) { |
|
43
|
1 |
|
return true; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
2 |
|
return self::isClassSameLazy($className, $validClass) ?: ($validClass instanceof $className); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
3 |
|
private static function validateParameters(string $className, $validClass): void |
|
50
|
|
|
{ |
|
51
|
3 |
|
if (!class_exists($className) && !interface_exists($className)) { |
|
52
|
1 |
|
throw new InvalidArgumentException(sprintf('The class/interface %s does not exist', $className)); |
|
53
|
|
|
} |
|
54
|
2 |
|
if (!\is_object($validClass)) { |
|
55
|
|
|
throw new InvalidArgumentException(sprintf('The $validClass parameter %s is not an object', $validClass)); |
|
56
|
|
|
} |
|
57
|
2 |
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** @throws ReflectionException */ |
|
60
|
2 |
|
private static function isClassSameLazy(string $className, $validClass): bool |
|
61
|
|
|
{ |
|
62
|
2 |
|
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
|
2 |
|
return false; |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|