BindValidator   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 15
eloc 14
c 2
b 0
f 0
dl 0
loc 59
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A to() 0 11 5
A isNullInterceptorBinding() 0 3 3
A constructor() 0 4 4
A toProvider() 0 13 3
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
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...
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