ConditionGenerator   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 2
dl 0
loc 69
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A defDefinition() 0 6 1
B code() 0 26 5
1
<?php declare(strict_types = 1);
2
/**
3
 * Created by Vitaly Iegorov <[email protected]>.
4
 * on 03.04.17 at 08:02
5
 */
6
7
namespace samsonframework\generator;
8
9
/**
10
 * Class ConditionGenerator
11
 *
12
 * @author Vitaly Egorov <[email protected]>
13
 */
14
class ConditionGenerator extends AbstractGenerator
15
{
16
    use CodeTrait;
17
18
    /** @var string Condition statement definition */
19
    protected $definition = '';
20
21
    /** @var bool If condition statement is nested */
22
    protected $nested;
23
24
    /**
25
     * ConditionGenerator constructor.
26
     *
27
     * @param bool                   $nested Flag if condition statement is nested
28
     * @param AbstractGenerator|null $parent Parent generator
29
     */
30
    public function __construct(bool $nested = false, AbstractGenerator $parent = null)
31
    {
32
        $this->nested = $nested;
33
34
        parent::__construct($parent);
35
    }
36
37
    /**
38
     * Set condition statement definition.
39
     *
40
     * @param string $definition Condition statement definition
41
     *
42
     * @return ConditionGenerator Condition generator
43
     */
44
    public function defDefinition(string $definition): ConditionGenerator
45
    {
46
        $this->definition = $definition;
47
48
        return $this;
49
    }
50
51
    /**
52
     * @inheritdoc
53
     *
54
     * @throws \Exception If condition is not nested and definition is not defined
55
     */
56
    public function code(): string
57
    {
58
        $innerIndentation = $this->indentation(1);
59
60
        // Generate condition statement definition code
61
        if ($this->definition === '') {
62
            if ($this->nested) { // Empty definition means else statement
63
                $formattedCode =  ["\n".'} else {'];
64
            } else {
65
                throw new \Exception('Cannot create not nested condition statement with empty definition');
66
            }
67
        } else { // Regular condition statement beginning
68
            $formattedCode = [
69
                ($this->nested
70
                    ? "\n".'} elseif ('
71
                    : 'if (') . $this->definition . ') {'
72
            ];
73
        }
74
75
        // Prepend inner indentation to code
76
        foreach ($this->code as $codeLine) {
77
            $formattedCode[] = $innerIndentation . $codeLine;
78
        }
79
80
        return implode("\n", $formattedCode);
81
    }
82
}
83