Passed
Pull Request — master (#78)
by Dmitriy
02:32
created

CallableDefinition::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Factory\Definition;
6
7
use Psr\Container\ContainerInterface;
8
use ReflectionMethod;
9
use Yiisoft\Injector\Injector;
10
11
use function is_array;
12
use function is_object;
13
14
class CallableDefinition implements DefinitionInterface
15
{
16
    /**
17
     * @var array|callable
18
     * @psalm-var callable|array{0:class-string,1:string}
19
     */
20
    private $method;
21
22
    /**
23
     * @param array|callable $method
24
     *
25
     * @psalm-param callable|array{0:class-string,1:string} $method
26
     */
27 4
    public function __construct($method)
28
    {
29 4
        $this->method = $method;
30 4
    }
31
32 4
    public function resolve(ContainerInterface $container)
33
    {
34 4
        $callable = $this->prepareCallable($this->method, $container);
35
36
        /** @psalm-suppress MixedMethodCall */
37 4
        return $container->get(Injector::class)->invoke($callable);
38
    }
39
40
    /**
41
     * @param array|callable $callable
42
     *
43
     * @psalm-param callable|array{0:class-string,1:string} $callable
44
     */
45 4
    private function prepareCallable($callable, ContainerInterface $container): callable
46
    {
47 4
        if (is_array($callable) && !is_object($callable[0])) {
48 2
            $reflection = new ReflectionMethod($callable[0], $callable[1]);
49 2
            if (!$reflection->isStatic()) {
50
                /** @var mixed */
51 1
                $callable[0] = $container->get($callable[0]);
52
            }
53
        }
54
55 4
        return $callable;
56
    }
57
}
58