Skip to content

Commit 56e0ce3

Browse files
committed
PhpFile: added addBody() for global code [WIP]
1 parent 4280604 commit 56e0ce3

File tree

5 files changed

+33
-0
lines changed

5 files changed

+33
-0
lines changed

src/PhpGenerator/PhpFile.php

+21
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99

1010
namespace Nette\PhpGenerator;
1111

12+
use JetBrains\PhpStorm\Language;
13+
1214

1315
/**
1416
* Definition of a PHP file.
@@ -25,6 +27,7 @@ final class PhpFile
2527
/** @var PhpNamespace[] */
2628
private array $namespaces = [];
2729
private bool $strictTypes = false;
30+
private string $body = '';
2831

2932

3033
public static function fromCode(string $code): self
@@ -110,6 +113,24 @@ public function addNamespace(string|PhpNamespace $namespace): PhpNamespace
110113
}
111114

112115

116+
/** @param ?mixed[] $args */
117+
public function addBody(
118+
#[Language('PHP')]
119+
string $code,
120+
?array $args = null,
121+
): static
122+
{
123+
$this->body .= ($args === null ? $code : (new Dumper)->format($code, ...$args)) . "\n";
124+
return $this;
125+
}
126+
127+
128+
public function getBody(): string
129+
{
130+
return $this->body;
131+
}
132+
133+
113134
/**
114135
* Removes the namespace from the file.
115136
*/

src/PhpGenerator/Printer.php

+4
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,10 @@ public function printFile(PhpFile $file): string
287287
}
288288
}
289289

290+
if ($tmp = $file->getBody()) {
291+
$namespaces[] = $tmp;
292+
}
293+
290294
return "<?php\n"
291295
. ($file->getComment() ? "\n" . $this->printDocComment($file) : '')
292296
. "\n"

tests/PhpGenerator/PhpFile.phpt

+2
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ $file->addFunction('Baz\f2')
7878
->setReturnType('Foo\B');
7979

8080

81+
$file->addBody('// global contents');
82+
8183
sameFile(__DIR__ . '/expected/PhpFile.regular.expect', (string) $file);
8284

8385
$file->addClass('H');

tests/PhpGenerator/expected/PhpFile.bracketed.expect

+3
Original file line numberDiff line numberDiff line change
@@ -83,3 +83,6 @@ namespace FooBar
8383
{
8484
}
8585
}
86+
87+
88+
// global contents

tests/PhpGenerator/expected/PhpFile.regular.expect

+3
Original file line numberDiff line numberDiff line change
@@ -59,3 +59,6 @@ trait G
5959
function f2(): \Foo\B
6060
{
6161
}
62+
63+
64+
// global contents

0 commit comments

Comments
 (0)