Skip to content

Commit 9ce5523

Browse files
committed
Printer: added $declareOnOpenTag option
1 parent 8ed5fd8 commit 9ce5523

2 files changed

Lines changed: 66 additions & 2 deletions

File tree

src/PhpGenerator/Printer.php

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ class Printer
2626
public bool $bracesOnNextLine = true;
2727
public bool $singleParameterOnOneLine = false;
2828
public bool $omitEmptyNamespaces = true;
29+
public bool $declareOnOpenTag = false;
2930
protected ?PhpNamespace $namespace = null;
3031
protected ?Dumper $dumper;
3132
private bool $resolveTypes = true;
@@ -286,10 +287,12 @@ public function printFile(PhpFile $file): string
286287
}
287288
}
288289

289-
return "<?php\n"
290+
$strictTypes = $file->hasStrictTypes();
291+
return '<?php' . ($strictTypes && $this->declareOnOpenTag ? ' declare(strict_types=1);' : '')
292+
. "\n"
290293
. ($file->getComment() ? "\n" . $this->printDocComment($file) : '')
291294
. "\n"
292-
. ($file->hasStrictTypes() ? "declare(strict_types=1);\n\n" : '')
295+
. ($strictTypes && !$this->declareOnOpenTag ? "declare(strict_types=1);\n\n" : '')
293296
. implode("\n\n", $namespaces);
294297
}
295298

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
<?php declare(strict_types=1);
2+
3+
use Nette\PhpGenerator\PhpFile;
4+
use Tester\Assert;
5+
6+
require __DIR__ . '/../bootstrap.php';
7+
8+
9+
test('file with singleLineOpenTag and strict types', function () {
10+
$file = new PhpFile;
11+
$file->addComment('This file is auto-generated. DO NOT EDIT!');
12+
$file->setStrictTypes();
13+
$file->addClass('A');
14+
15+
$printer = new Nette\PhpGenerator\Printer;
16+
$printer->declareOnOpenTag = true;
17+
18+
Assert::match(<<<'XX'
19+
<?php declare(strict_types=1);
20+
21+
/**
22+
* This file is auto-generated. DO NOT EDIT!
23+
*/
24+
25+
class A
26+
{
27+
}
28+
29+
XX, $printer->printFile($file));
30+
});
31+
32+
33+
test('singleLineOpenTag without comment', function () {
34+
$file = new PhpFile;
35+
$file->setStrictTypes();
36+
$file->addClass('A');
37+
38+
$printer = new Nette\PhpGenerator\Printer;
39+
$printer->declareOnOpenTag = true;
40+
41+
Assert::match(<<<'XX'
42+
<?php declare(strict_types=1);
43+
44+
class A
45+
{
46+
}
47+
48+
XX, $printer->printFile($file));
49+
});
50+
51+
52+
test('singleLineOpenTag has no effect without strict types', function () {
53+
$file = new PhpFile;
54+
$file->addClass('A');
55+
56+
$printerA = new Nette\PhpGenerator\Printer;
57+
$printerB = new Nette\PhpGenerator\Printer;
58+
$printerB->declareOnOpenTag = true;
59+
60+
Assert::same($printerA->printFile($file), $printerB->printFile($file));
61+
});

0 commit comments

Comments
 (0)