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

Argument::buildOptional()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 3
nop 0
dl 0
loc 15
ccs 9
cts 9
cp 1
crap 3
rs 9.4285
c 0
b 0
f 0
1
<?php
2
declare(strict_types = 1);
3
4
namespace Innmind\Compose\Compilation;
5
6
use Innmind\Compose\{
7
    Definition\Argument as Definition,
8
    Exception\LogicException
9
};
10
11
final class Argument
12
{
13
    private $definition;
14
15 7
    public function __construct(Definition $argument)
16
    {
17 7
        $this->definition = $argument;
18 7
    }
19
20 6
    public function __toString(): string
21
    {
22 6
        $method = new MethodName($this->definition->name());
23
        $code = <<<PHP
24 6
    public function $method()
25
    {
26 6
        if (\$this->arguments->contains('{$this->definition->name()}')) {
27 6
            return \$this->arguments->get('{$this->definition->name()}');
28
        }
29
30 6
        {$this->buildDefault()}
31 6
        {$this->buildOptional()}
32
    }
33
PHP;
34
35 6
        return $code;
36
    }
37
38 6
    private function buildDefault(): string
39
    {
40 6
        if (!$this->definition->hasDefault()) {
41 5
            return '';
42
        }
43
44 3
        return sprintf(
45 3
            'return $this->%s();',
46 3
            new MethodName($this->definition->default())
47
        );
48
    }
49
50 6
    private function buildOptional(): string
51
    {
52 6
        if ($this->definition->hasDefault()) {
53 3
            return '';
54
        }
55
56 5
        if (!$this->definition->optional()) {
57 4
            return sprintf(
58 4
                'throw new %s(\'Missing argument "%s"\');',
59 4
                LogicException::class,
60 4
                $this->definition->name()
61
            );
62
        }
63
64 3
        return 'return null;';
65
    }
66
}
67