Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion src/PhpFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@

class PhpFile extends DependencyAwareGenerator
{
public const STRICT = 'strict_types';

protected string $namespace = '';
protected string $name;
protected ?Comment $comment;
Expand All @@ -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 <<<CODE
<?php
$namespace{$this->buildUseStatements()}
$declares$namespace{$this->buildUseStatements()}
$classes
CODE;
}
Expand Down
5 changes: 4 additions & 1 deletion tests/PhpFileTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -59,6 +60,7 @@ public function fullBuild(): PhpFile

$this->expectOutputString(<<<'CODE'
<?php
declare(strict_types=1);

namespace App\Converter;

Expand Down Expand Up @@ -109,6 +111,7 @@ private static function getPhpFile(): PhpFile
*/
public function modifyFile(PhpFile $file): PhpFile
{
$file->removeStrict();
$file->removeClass('ArrayConverter');
$file->removeUse('Symfony\Validator\Converters');
$file->addClass(new PhpClass('YetAnotherClass'));
Expand Down