BindValidator::to()   A
last analyzed

Complexity

Conditions 5
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
c 0
b 0
f 0
dl 0
loc 11
rs 9.6111
cc 5
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\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
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); // @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