1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Ray\Di; |
6
|
|
|
|
7
|
|
|
use Ray\Aop\MethodInterceptor; |
8
|
|
|
use Ray\Aop\NullInterceptor; |
9
|
|
|
use Ray\Aop\ReflectionClass; |
10
|
|
|
use Ray\Di\Exception\InvalidProvider; |
11
|
|
|
use Ray\Di\Exception\InvalidType; |
12
|
|
|
use Ray\Di\Exception\NotFound; |
13
|
|
|
|
14
|
|
|
use function class_exists; |
15
|
|
|
use function interface_exists; |
16
|
|
|
|
17
|
|
|
final class BindValidator |
18
|
|
|
{ |
19
|
|
|
public function constructor(string $interface): void |
20
|
|
|
{ |
21
|
|
|
if ($interface && ! interface_exists($interface) && ! class_exists($interface)) { |
22
|
|
|
throw new NotFound($interface); |
23
|
|
|
} |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* To validator |
28
|
|
|
* |
29
|
|
|
* @param class-string<T> $class |
|
|
|
|
30
|
|
|
* |
31
|
|
|
* @return ReflectionClass<T> |
32
|
|
|
* |
33
|
|
|
* @template T of object |
34
|
|
|
*/ |
35
|
|
|
public function to(string $interface, string $class): ReflectionClass |
36
|
|
|
{ |
37
|
|
|
if (! class_exists($class)) { |
38
|
|
|
throw new NotFound($class); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
if (! $this->isNullInterceptorBinding($class, $interface) && interface_exists($interface) && ! (new ReflectionClass($class))->implementsInterface($interface)) { |
42
|
|
|
throw new InvalidType("[{$class}] is no implemented [{$interface}] interface"); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
return new ReflectionClass($class); // @phpstan-ignore-line |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* toProvider validator |
50
|
|
|
* |
51
|
|
|
* @phpstan-param class-string $provider |
52
|
|
|
* |
53
|
|
|
* @psalm-return ReflectionClass |
54
|
|
|
* @phpstan-return ReflectionClass<object> |
55
|
|
|
* |
56
|
|
|
* @throws NotFound |
57
|
|
|
*/ |
58
|
|
|
public function toProvider(string $provider): ReflectionClass |
59
|
|
|
{ |
60
|
|
|
if (! class_exists($provider)) { |
61
|
|
|
/** @psalm-suppress MixedArgument -- should be string */ |
62
|
|
|
throw new NotFound($provider); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
$reflectioClass = new ReflectionClass($provider); |
66
|
|
|
if (! $reflectioClass->implementsInterface(ProviderInterface::class)) { |
67
|
|
|
throw new InvalidProvider($provider); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
return $reflectioClass; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
private function isNullInterceptorBinding(string $class, string $interface): bool |
74
|
|
|
{ |
75
|
|
|
return $class === NullInterceptor::class && interface_exists($interface) && (new ReflectionClass($interface))->implementsInterface(MethodInterceptor::class); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|