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
|
|
|
|