From 20e37e999fcf87078a7f10c8ef6d315c712bdddb Mon Sep 17 00:00:00 2001 From: Farrokh Ghamsary Date: Tue, 13 Dec 2022 08:58:09 +0100 Subject: [PATCH] Add possibility to add strict_type or other declares on the PhpFile --- src/PhpFile.php | 37 ++++++++++++++++++++++++++++++++++++- tests/PhpFileTest.php | 5 ++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/PhpFile.php b/src/PhpFile.php index 0b4deac..b04b64e 100644 --- a/src/PhpFile.php +++ b/src/PhpFile.php @@ -12,6 +12,8 @@ class PhpFile extends DependencyAwareGenerator { + public const STRICT = 'strict_types'; + protected string $namespace = ''; protected string $name; protected ?Comment $comment; @@ -33,14 +35,47 @@ public static function new(string $name = ''): self return new self($name); } + public function addDeclare(string $name, $value): self + { + $this->declares[$name] = Utils::stringify($value); + + return $this; + } + + public function removeDeclare(string $name): self + { + unset($this->declares[$name]); + + return $this; + } + + public function addStrict(): self + { + $this->addDeclare(self::STRICT, 1); + + return $this; + } + + public function removeStrict(): self + { + $this->removeDeclare(self::STRICT); + + return $this; + } + public function generate(): string { + $declareItems = []; + foreach ($this->declares as $key => $value) { + $declareItems[] = "declare($key=$value);"; + } + $declares = count($declareItems) > 0 ? implode("\n", $declareItems) . "\n" : ''; $namespace = $this->namespace ? "\nnamespace $this->namespace;\n" : ''; $classes = implode("\n\n", $this->classes); return <<buildUseStatements()} + $declares$namespace{$this->buildUseStatements()} $classes CODE; } diff --git a/tests/PhpFileTest.php b/tests/PhpFileTest.php index b61ff58..ff2a3ea 100644 --- a/tests/PhpFileTest.php +++ b/tests/PhpFileTest.php @@ -24,7 +24,8 @@ public function fullBuild(): PhpFile $file = PhpFile::new() ->setNamespace('App\Converter') ->addUseGroup('Symfony\Validator\Converters', 'NotNull', 'Symfony\Validator\Converters\Length') - ->setComment('This file was generated and should not be modified manually.'); + ->setComment('This file was generated and should not be modified manually.') + ->addStrict(); $class = $file->createClass('ArrayConverter') ->setAbstract() @@ -59,6 +60,7 @@ public function fullBuild(): PhpFile $this->expectOutputString(<<<'CODE' removeStrict(); $file->removeClass('ArrayConverter'); $file->removeUse('Symfony\Validator\Converters'); $file->addClass(new PhpClass('YetAnotherClass'));