Skip to content

Commit 03eb652

Browse files
committed
PhpFile: added setStrictTypes()
1 parent b736aed commit 03eb652

File tree

5 files changed

+42
-0
lines changed

5 files changed

+42
-0
lines changed

readme.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -464,6 +464,7 @@ PHP files can contains multiple classes, namespaces and comments:
464464
```php
465465
$file = new Nette\PhpGenerator\PhpFile;
466466
$file->addComment('This file is auto-generated.');
467+
$file->setStrictTypes(); // adds declare(strict_types=1)
467468

468469
$namespace = $file->addNamespace('Foo');
469470
$class = $namespace->addClass('A');
@@ -484,6 +485,8 @@ Result:
484485
* This file is auto-generated.
485486
*/
486487

488+
declare(strict_types=1);
489+
487490
namespace Foo;
488491

489492
class A

src/PhpGenerator/PhpFile.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@ final class PhpFile
2828
/** @var PhpNamespace[] */
2929
private $namespaces = [];
3030

31+
/** @var bool */
32+
private $strictTypes = false;
33+
3134

3235
public function addClass(string $name): ClassType
3336
{
@@ -74,6 +77,23 @@ public function getNamespaces(): array
7477
}
7578

7679

80+
/**
81+
* Adds declare(strict_types=1) to output.
82+
* @return static
83+
*/
84+
public function setStrictTypes(bool $on = true): self
85+
{
86+
$this->strictTypes = $on;
87+
return $this;
88+
}
89+
90+
91+
public function getStrictTypes(): bool
92+
{
93+
return $this->strictTypes;
94+
}
95+
96+
7797
public function __toString(): string
7898
{
7999
try {

src/PhpGenerator/Printer.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,7 @@ public function printFile(PhpFile $file): string
176176
return Strings::normalize(
177177
"<?php\n"
178178
. ($file->getComment() ? "\n" . Helpers::formatDocComment($file->getComment() . "\n") . "\n" : '')
179+
. ($file->getStrictTypes() ? "declare(strict_types=1);\n\n" : '')
179180
. implode("\n\n", $namespaces)
180181
) . "\n";
181182
}

tests/PhpGenerator/PhpFile.phpt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,3 +80,10 @@ $file = new PhpFile;
8080
$file->addClass('A');
8181

8282
sameFile(__DIR__ . '/expected/PhpFile.globalNamespace.expect', (string) $file);
83+
84+
$file = new PhpFile;
85+
$file->addComment('This file is auto-generated. DO NOT EDIT!');
86+
$file->setStrictTypes();
87+
$file->addClass('A');
88+
89+
sameFile(__DIR__ . '/expected/PhpFile.strictTypes.expect', (string) $file);
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?php
2+
3+
/**
4+
* This file is auto-generated. DO NOT EDIT!
5+
*/
6+
7+
declare(strict_types=1);
8+
9+
class A
10+
{
11+
}

0 commit comments

Comments
 (0)