From 9a4f92adcb07c1bf778b8e137c54f7da9c339579 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Mon, 6 Aug 2018 16:13:30 +0200 Subject: [PATCH] added PhpNamespace::add() [Closes #27] --- readme.md | 4 ++++ src/PhpGenerator/PhpNamespace.php | 19 +++++++++++++++++-- tests/PhpGenerator/PhpNamespace.add.phpt | 23 +++++++++++++++++++++++ 3 files changed, 44 insertions(+), 2 deletions(-) create mode 100644 tests/PhpGenerator/PhpNamespace.add.phpt diff --git a/readme.md b/readme.md index 33b91ef2..255a3d46 100644 --- a/readme.md +++ b/readme.md @@ -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. diff --git a/src/PhpGenerator/PhpNamespace.php b/src/PhpGenerator/PhpNamespace.php index 55893f51..615360cd 100644 --- a/src/PhpGenerator/PhpNamespace.php +++ b/src/PhpGenerator/PhpNamespace.php @@ -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; } diff --git a/tests/PhpGenerator/PhpNamespace.add.phpt b/tests/PhpGenerator/PhpNamespace.add.phpt new file mode 100644 index 00000000..9b9ee7f7 --- /dev/null +++ b/tests/PhpGenerator/PhpNamespace.add.phpt @@ -0,0 +1,23 @@ +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());