ray-di /
Ray.Di
| 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 | use function sprintf; |
||
| 17 | |||
| 18 | final class BindValidator |
||
| 19 | { |
||
| 20 | public function constructor(string $interface): void |
||
| 21 | { |
||
| 22 | if ($interface && ! interface_exists($interface) && ! class_exists($interface)) { |
||
| 23 | throw new NotFound($interface); |
||
| 24 | } |
||
| 25 | } |
||
| 26 | |||
| 27 | /** |
||
| 28 | * To validator |
||
| 29 | * |
||
| 30 | * @param class-string<T> $class |
||
|
0 ignored issues
–
show
Documentation
Bug
introduced
by
Loading history...
|
|||
| 31 | * |
||
| 32 | * @return ReflectionClass<T> |
||
| 33 | * |
||
| 34 | * @template T of object |
||
| 35 | */ |
||
| 36 | public function to(string $interface, string $class): ReflectionClass |
||
| 37 | { |
||
| 38 | if (! class_exists($class)) { |
||
| 39 | throw new NotFound($class); |
||
| 40 | } |
||
| 41 | |||
| 42 | if (! $this->isNullInterceptorBinding($class, $interface) && interface_exists($interface) && ! (new ReflectionClass($class))->implementsInterface($interface)) { |
||
| 43 | throw new InvalidType(sprintf('[%s] is no implemented [%s] interface', $class, $interface)); |
||
| 44 | } |
||
| 45 | |||
| 46 | return new ReflectionClass($class); |
||
| 47 | } |
||
| 48 | |||
| 49 | /** |
||
| 50 | * toProvider validator |
||
| 51 | * |
||
| 52 | * @phpstan-param class-string $provider |
||
| 53 | * |
||
| 54 | * @psalm-return ReflectionClass |
||
| 55 | * @phpstan-return ReflectionClass<object> |
||
| 56 | * |
||
| 57 | * @throws NotFound |
||
| 58 | */ |
||
| 59 | public function toProvider(string $provider): ReflectionClass |
||
| 60 | { |
||
| 61 | if (! class_exists($provider)) { |
||
| 62 | /** @psalm-suppress MixedArgument -- should be string */ |
||
| 63 | throw new NotFound($provider); |
||
| 64 | } |
||
| 65 | |||
| 66 | $reflectioClass = new ReflectionClass($provider); |
||
| 67 | if (! $reflectioClass->implementsInterface(ProviderInterface::class)) { |
||
| 68 | throw new InvalidProvider($provider); |
||
| 69 | } |
||
| 70 | |||
| 71 | return $reflectioClass; |
||
| 72 | } |
||
| 73 | |||
| 74 | private function isNullInterceptorBinding(string $class, string $interface): bool |
||
| 75 | { |
||
| 76 | return $class === NullInterceptor::class && interface_exists($interface) && (new ReflectionClass($interface))->implementsInterface(MethodInterceptor::class); |
||
| 77 | } |
||
| 78 | } |
||
| 79 |