Passed
Push — develop ( b5b773...c3bc05 )
by Baptiste
02:13
created

ServiceFactory::__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
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types = 1);
3
4
namespace Innmind\Compose\Definition\Service\Constructor;
5
6
use Innmind\Compose\{
7
    Definition\Service\Constructor,
8
    Exception\ValueNotSupported,
9
    Lazy,
10
    Compilation\Service\Constructor as CompiledConstructor,
11
    Compilation\Service\Constructor\ServiceFactory as CompiledServiceFactory,
12
    Compilation\Service\Argument as CompiledArgument,
13
};
14
use Innmind\Immutable\{
15
    Str,
16
    Sequence,
17
};
18
19
final class ServiceFactory implements Constructor
20
{
21
    private $method;
22
23 4
    private function __construct(string $method)
24
    {
25 4
        $this->method = $method;
26 4
    }
27
28
    /**
29
     * {@inheritdoc}
30
     */
31 18
    public static function fromString(Str $value): Constructor
32
    {
33 18
        if (!$value->matches('~^\$factory->\S+$~')) {
34 14
            throw new ValueNotSupported((string) $value);
35
        }
36
37 4
        [, $method] = $value->split('->');
38
39 4
        return new self((string) $method);
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function __invoke(...$arguments): object
46
    {
47 2
        $arguments = Sequence::of(...$arguments)->map(static function($argument) {
48 2
            if ($argument instanceof Lazy) {
49 1
                return $argument->load();
50
            }
51
52 2
            return $argument;
53 2
        });
54
55 2
        return $arguments->first()->{$this->method}(...$arguments->drop(1));
56
    }
57
58 1
    public function compile(CompiledArgument ...$arguments): CompiledConstructor
59
    {
60 1
        return new CompiledServiceFactory($this->method, ...$arguments);
61
    }
62
63 1
    public function __toString(): string
64
    {
65 1
        return sprintf('$factory->%s', $this->method);
66
    }
67
}
68