Passed
Pull Request — master (#1104)
by Aleksei
26:20
created

ActionResolver   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
eloc 25
dl 0
loc 53
ccs 29
cts 29
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A pathToReflection() 0 14 2
A validateControllerMethod() 0 25 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiral\Interceptors\Internal;
6
7
use Spiral\Interceptors\Exception\TargetCallException;
8
9
/**
10
 * @internal
11
 */
12
final class ActionResolver
13
{
14
    /**
15
     * @psalm-assert class-string $controller
16
     * @psalm-assert non-empty-string $action
17
     *
18
     * @throws TargetCallException
19
     */
20 58
    public static function pathToReflection(string $controller, string $action): \ReflectionMethod
21
    {
22
        try {
23
            /** @psalm-suppress ArgumentTypeCoercion */
24 58
            $method = new \ReflectionMethod($controller, $action);
25 11
        } catch (\ReflectionException $e) {
26 11
            throw new TargetCallException(
27 11
                \sprintf('Invalid action `%s`->`%s`', $controller, $action),
28 11
                TargetCallException::BAD_ACTION,
29 11
                $e
30 11
            );
31
        }
32
33 47
        return $method;
34
    }
35
36
    /**
37
     * @throws TargetCallException
38
     * @psalm-assert object|null $controller
39
     */
40 54
    public static function validateControllerMethod(\ReflectionMethod $method, mixed $controller = null): void
41
    {
42 54
        if ($method->isStatic() || !$method->isPublic()) {
43 4
            throw new TargetCallException(
44 4
                \sprintf(
45 4
                    'Invalid action `%s`->`%s`',
46 4
                    $method->getDeclaringClass()->getName(),
47 4
                    $method->getName(),
48 4
                ),
49 4
                TargetCallException::BAD_ACTION
50 4
            );
51
        }
52
53 50
        if ($controller === null) {
54 45
            return;
55
        }
56
57 5
        if (!\is_object($controller) || !$method->getDeclaringClass()->isInstance($controller)) {
58 1
            throw new TargetCallException(
59 1
                \sprintf(
60 1
                    'Invalid controller. Expected instance of `%s`, got `%s`.',
61 1
                    $method->getDeclaringClass()->getName(),
62 1
                    \get_debug_type($controller),
63 1
                ),
64 1
                TargetCallException::INVALID_CONTROLLER,
65 1
            );
66
        }
67
    }
68
}
69