|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Murtukov\PHPCodeGenerator; |
|
6
|
|
|
|
|
7
|
|
|
class Instance extends DependencyAwareGenerator |
|
8
|
|
|
{ |
|
9
|
|
|
private array $args; |
|
10
|
|
|
private string $qualifier; |
|
11
|
|
|
public bool $multiline = false; |
|
12
|
|
|
|
|
13
|
10 |
|
public function __construct(string $qualifier, ...$args) |
|
14
|
|
|
{ |
|
15
|
10 |
|
$this->qualifier = $this->resolveQualifier($qualifier); |
|
16
|
10 |
|
$this->args = $args; |
|
17
|
10 |
|
} |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @throws Exception\UnrecognizedValueTypeException |
|
21
|
|
|
*/ |
|
22
|
13 |
|
public function generate(): string |
|
23
|
|
|
{ |
|
24
|
13 |
|
if (empty($this->args)) { |
|
25
|
11 |
|
return "new $this->qualifier()"; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
3 |
|
if ($this->multiline) { |
|
29
|
1 |
|
$args = "\n"; |
|
30
|
1 |
|
$suffix = ",\n"; |
|
31
|
|
|
} else { |
|
32
|
3 |
|
$args = ''; |
|
33
|
3 |
|
$suffix = ', '; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
3 |
|
foreach ($this->args as $arg) { |
|
37
|
3 |
|
$args .= Utils::stringify($arg).$suffix; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
3 |
|
if ($this->multiline) { |
|
41
|
1 |
|
$args = Utils::indent($args, false); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
3 |
|
$args = rtrim($args, ', '); |
|
45
|
|
|
|
|
46
|
3 |
|
return "new $this->qualifier($args)"; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
1 |
|
public function addArgument($arg): self |
|
50
|
|
|
{ |
|
51
|
1 |
|
$this->args[] = $arg; |
|
52
|
|
|
|
|
53
|
1 |
|
return $this; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
1 |
|
public static function multiline(string $qualifier, ...$args) |
|
57
|
|
|
{ |
|
58
|
1 |
|
$instance = new self($qualifier, ...$args); |
|
59
|
1 |
|
$instance->multiline = true; |
|
60
|
|
|
|
|
61
|
1 |
|
return $instance; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
9 |
|
public static function new(string $qualifier, ...$args) |
|
65
|
|
|
{ |
|
66
|
9 |
|
return new self($qualifier, ...$args); |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
1 |
|
public function setMultiline(): self |
|
70
|
|
|
{ |
|
71
|
1 |
|
$this->multiline = true; |
|
72
|
|
|
|
|
73
|
1 |
|
return $this; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
1 |
|
public function setInline() |
|
77
|
|
|
{ |
|
78
|
1 |
|
$this->multiline = false; |
|
79
|
|
|
|
|
80
|
1 |
|
return $this; |
|
81
|
|
|
} |
|
82
|
|
|
} |
|
83
|
|
|
|