Completed
Push — develop ( 15ec3c...8b62a8 )
by Baptiste
02:19
created

Pair::compile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
declare(strict_types = 1);
3
4
namespace Innmind\Compose\Definition\Service\Argument;
5
6
use Innmind\Compose\{
7
    Definition\Service\Argument,
8
    Definition\Service\Arguments,
9
    Services,
10
    Compilation\Service\Argument as CompiledArgument,
11
    Compilation\Service\Argument\Pair as CompiledPair,
12
    Exception\ValueNotSupported,
13
    Exception\LogicException
14
};
15
use Innmind\Immutable\{
16
    Pair as ImmutablePair,
17
    StreamInterface,
18
    Str
19
};
20
21
final class Pair implements Argument
22
{
23
    private $key;
24
    private $value;
25
26 10
    private function __construct(Argument $key, Argument $value)
27
    {
28 10
        if ($key instanceof Unwind || $value instanceof Unwind) {
29 2
            throw new LogicException;
30
        }
31
32 8
        $this->key = $key;
33 8
        $this->value = $value;
34 8
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39 17
    public static function fromValue($value, Arguments $arguments): Argument
40
    {
41 17
        if (!is_string($value)) {
42 10
            throw new ValueNotSupported;
43
        }
44
45 12
        $value = Str::of($value);
46
47 12
        if (!$value->matches('~^<\S+, ?\S+>$~')) {
48 11
            throw new ValueNotSupported((string) $value);
49
        }
50
51 10
        $components = $value->capture('~^<(?<key>\S+), ?(?<value>\S+)>$~');
52
53 10
        return new self(
54 10
            $arguments->load((string) $components->get('key')),
55 10
            $arguments->load((string) $components->get('value'))
56
        );
57
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62 2
    public function resolve(
63
        StreamInterface $built,
64
        Services $services
65
    ): StreamInterface {
66
        $key = $this
67 2
            ->key
68 2
            ->resolve(
69 2
                $built->clear(),
70 2
                $services
71
            )
72 2
            ->first();
73
        $value = $this
74 2
            ->value
75 2
            ->resolve(
76 2
                $built->clear(),
77 2
                $services
78
            )
79 2
            ->first();
80
81 2
        return $built->add(new ImmutablePair($key, $value));
82
    }
83
84 3
    public function compile(): CompiledArgument
85
    {
86 3
        return new CompiledPair(
87 3
            $this->key->compile(),
88 3
            $this->value->compile()
89
        );
90
    }
91
}
92