diff --git a/readme.md b/readme.md index 373b181e..f3d42a0b 100644 --- a/readme.md +++ b/readme.md @@ -449,6 +449,17 @@ class A } ``` +You can also add existing `ClassType` or `PhpNamespace` objects to the file: + +```php +$namespace = new Nette\PhpGenerator\PhpNamespace('Foo'); +$class = new Nette\PhpGenerator\ClassType('Demo'); + +$file = new Nette\PhpGenerator\PhpFile; +$file->add($namespace); +$file->add($class); +``` + Generate using Reflection ------------------------- diff --git a/src/PhpGenerator/PhpFile.php b/src/PhpGenerator/PhpFile.php index c43a7bc0..842c15e4 100644 --- a/src/PhpGenerator/PhpFile.php +++ b/src/PhpGenerator/PhpFile.php @@ -29,6 +29,31 @@ final class PhpFile private $namespaces = []; + /** + * @param ClassType|PhpNamespace $item + * @return static + */ + public function add($item): self + { + if ($item instanceof PhpNamespace) { + $this->namespaces[$item->getName()] = $item; + foreach ($this->namespaces as $namespace) { + $namespace->setBracketedSyntax(count($this->namespaces) > 1 && isset($this->namespaces[''])); + } + + } elseif ($item instanceof ClassType) { + $namespace = $item->getNamespace(); + $this->addNamespace($namespace ? $namespace->getName() : '') + ->add($item); + + } else { + throw new Nette\InvalidArgumentException('Argument must be ClassType|PhpNamespace.'); + } + + return $this; + } + + public function addClass(string $name): ClassType { return $this @@ -56,10 +81,7 @@ public function addTrait(string $name): ClassType public function addNamespace(string $name): PhpNamespace { if (!isset($this->namespaces[$name])) { - $this->namespaces[$name] = new PhpNamespace($name); - foreach ($this->namespaces as $namespace) { - $namespace->setBracketedSyntax(count($this->namespaces) > 1 && isset($this->namespaces[''])); - } + $this->add(new PhpNamespace($name)); } return $this->namespaces[$name]; } diff --git a/tests/PhpGenerator/PhpFile.add.phpt b/tests/PhpGenerator/PhpFile.add.phpt new file mode 100644 index 00000000..f37e7f65 --- /dev/null +++ b/tests/PhpGenerator/PhpFile.add.phpt @@ -0,0 +1,31 @@ +add(new stdClass); +}, Nette\InvalidArgumentException::class, 'Argument must be ClassType|PhpNamespace.'); + + +$file = (new PhpFile) + ->add($classA = new ClassType('A')) + ->add($classB = new ClassType('B', new PhpNamespace('X'))) + ->add(new PhpNamespace('Y')); + +$namespaces = $file->getNamespaces(); +Assert::same($namespaces[''], $classA->getNamespace()); +Assert::same($namespaces['X'], $classB->getNamespace()); +Assert::true(isset($namespaces['Y'])); + +Assert::true($namespaces['']->getBracketedSyntax()); +Assert::true($namespaces['X']->getBracketedSyntax()); +Assert::true($namespaces['Y']->getBracketedSyntax());