Completed
Push — 2.x ( 5b5305...7cc030 )
by Akihito
23s queued 12s
created

BindValidator::isNullInterceptorBinding()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 3
nc 3
nop 2
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\Di\Exception\InvalidProvider;
10
use Ray\Di\Exception\InvalidType;
11
use Ray\Di\Exception\NotFound;
12
use ReflectionClass;
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
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string<T> at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<T>.
Loading history...
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);
46
    }
47
48
    /**
49
     * toProvider validator
50
     *
51
     * @phpstan-param class-string $provider
52
     *
53
     * @return ReflectionClass<object>
54
     *
55
     * @throws NotFound
56
     */
57
    public function toProvider(string $provider): ReflectionClass
58
    {
59
        if (! class_exists($provider)) {
60
            /** @psalm-suppress MixedArgument -- should be string */
61
            throw new NotFound($provider);
62
        }
63
64
        if (! (new ReflectionClass($provider))->implementsInterface(ProviderInterface::class)) {
65
            throw new InvalidProvider($provider);
66
        }
67
68
        return new ReflectionClass($provider);
69
    }
70
71
    private function isNullInterceptorBinding(string $class, string $interface): bool
72
    {
73
        return $class === NullInterceptor::class && interface_exists($interface) && (new ReflectionClass($interface))->implementsInterface(MethodInterceptor::class);
74
    }
75
}
76