Skip to content

Commit

Permalink
added PhpNamespace::add() [Closes #27]
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Aug 9, 2018
1 parent ab39e29 commit 9a4f92a
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 2 deletions.
4 changes: 4 additions & 0 deletions readme.md
Expand Up @@ -390,6 +390,10 @@ $namespace = new Nette\PhpGenerator\PhpNamespace('Foo');
$class = $namespace->addClass('Task');
$interface = $namespace->addInterface('Countable');
$trait = $namespace->addTrait('NameAware');

// or
$class = new Nette\PhpGenerator\ClassType('Task');
$namespace->add($class);
```

If the class already exists, it will be overwritten.
Expand Down
19 changes: 17 additions & 2 deletions src/PhpGenerator/PhpNamespace.php
Expand Up @@ -145,10 +145,25 @@ public function unresolveName(string $name): string
}


public function addClass(string $name): ClassType
/**
* @return static
*/
public function add(ClassType $class): self
{
$name = $class->getName();
if (!$name) {
throw new Nette\InvalidArgumentException('Class does not have a name.');
}
$this->addUse($this->name . '\\' . $name);
return $this->classes[$name] = new ClassType($name, $this);
$this->classes[$name] = $class;
return $this;
}


public function addClass(string $name): ClassType
{
$this->add($class = new ClassType($name, $this));
return $class;
}


Expand Down
23 changes: 23 additions & 0 deletions tests/PhpGenerator/PhpNamespace.add.phpt
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

use Nette\PhpGenerator\ClassType;
use Nette\PhpGenerator\PhpNamespace;
use Tester\Assert;

require __DIR__ . '/../bootstrap.php';


Assert::exception(function () {
(new PhpNamespace('Foo'))->add(new ClassType);
}, Nette\InvalidArgumentException::class, 'Class does not have a name.');


$namespace = (new PhpNamespace('Foo'))
->add($classA = new ClassType('A'))
->add($classB = new ClassType('B', new PhpNamespace('X')));

// namespaces are not changed
Assert::null($classA->getNamespace());
Assert::same('X', $classB->getNamespace()->getName());

0 comments on commit 9a4f92a

Please sign in to comment.