-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodeWriter.php
More file actions
141 lines (112 loc) · 2.8 KB
/
CodeWriter.php
File metadata and controls
141 lines (112 loc) · 2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
<?php
declare(strict_types=1);
namespace Auroro\Code;
use Stringable;
final class CodeWriter implements Stringable
{
private int $level = 0;
/** @var list<string> */
private array $lines = [];
public function __construct(
private readonly CodeStyle $style = new CodeStyle(),
) {}
/**
* Emit a line at the current indent level.
*/
public function line(string $text): self
{
$this->lines[] = $this->currentIndent() . $text;
return $this;
}
/**
* Emit an empty line (no trailing whitespace).
*/
public function blank(): self
{
$this->lines[] = '';
return $this;
}
/**
* Emit a comment at the current indent level.
*/
public function comment(string $text): self
{
$this->lines[] = $this->currentIndent() . $this->style->commentPrefix . ' ' . $text;
return $this;
}
/**
* Emit raw text without auto-indent (pre-formatted content).
*/
public function raw(string $text): self
{
$this->lines[] = $text;
return $this;
}
/**
* Increase indent level.
*/
public function indent(): self
{
$this->level++;
return $this;
}
/**
* Decrease indent level (minimum 0).
*/
public function dedent(): self
{
$this->level = max(0, $this->level - 1);
return $this;
}
/**
* Emit a block: header + blockOpen, indent, body, dedent, blockClose.
*
* @param callable(self): void $body
*/
public function block(string $header, callable $body): self
{
$this->lines[] = $this->currentIndent() . $header . $this->style->blockOpen;
$this->level++;
$body($this);
$this->level--;
if ('' !== $this->style->blockClose) {
$this->lines[] = $this->currentIndent() . $this->style->blockClose;
}
return $this;
}
/**
* Indent, run body, dedent — no braces.
*
* @param callable(self): void $body
*/
public function indented(callable $body): self
{
$this->level++;
$body($this);
$this->level--;
return $this;
}
/**
* Re-indent another writer's lines at the current level.
*/
public function append(self $other): self
{
$indent = $this->currentIndent();
foreach ($other->lines as $line) {
$this->lines[] = '' === $line ? '' : $indent . $line;
}
return $this;
}
public function __toString(): string
{
return implode("\n", $this->lines);
}
public function isEmpty(): bool
{
return [] === $this->lines;
}
private function currentIndent(): string
{
return str_repeat($this->style->indent, $this->level);
}
}