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

ServiceFactory   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 47
ccs 18
cts 18
cp 1
rs 10
c 0
b 0
f 0
wmc 7

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 11 2
A __toString() 0 3 1
A fromString() 0 9 2
A compile() 0 3 1
A __construct() 0 3 1
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