From e4bb051a3da9af0c4c4d228f02e1df7d03447619 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Mon, 6 Aug 2018 19:43:32 +0200 Subject: [PATCH] added ClassType::add() [Closes #35] --- readme.md | 13 +++++++++++++ src/PhpGenerator/ClassType.php | 26 ++++++++++++++++++++++++++ tests/PhpGenerator/ClassType.add.phpt | 25 +++++++++++++++++++++++++ 3 files changed, 64 insertions(+) create mode 100644 tests/PhpGenerator/ClassType.add.phpt diff --git a/readme.md b/readme.md index 71fc9642..e289dc97 100644 --- a/readme.md +++ b/readme.md @@ -151,6 +151,19 @@ class Demo } ``` +You can also add existing `Method`, `Property` or `Constant` objects to the class: + +```php +$method = new Nette\PhpGenerator\Method('getHandle'); +$property = new Nette\PhpGenerator\Property('handle'); +$const = new Nette\PhpGenerator\Constant('ROLE'); + +$class = (new Nette\PhpGenerator\ClassType('Demo')) + ->add($method) + ->add($property) + ->add($const); +``` + Tabs versus spaces ------------------ diff --git a/src/PhpGenerator/ClassType.php b/src/PhpGenerator/ClassType.php index a4ae4bb7..66787619 100644 --- a/src/PhpGenerator/ClassType.php +++ b/src/PhpGenerator/ClassType.php @@ -400,6 +400,32 @@ public function addMethod(string $name): Method } + /** + * @param Method|Property|Constant $member + * @return static + */ + public function add($member): self + { + if ($member instanceof Method) { + if ($this->type === 'interface') { + $member->setBody(null); + } + $this->methods[$member->getName()] = $member; + + } elseif ($member instanceof Property) { + $this->properties[$member->getName()] = $member; + + } elseif ($member instanceof Constant) { + $this->consts[$member->getName()] = $member; + + } else { + throw new Nette\InvalidArgumentException('Argument must be Method|Property|Constant.'); + } + + return $this; + } + + private function validate(array $names): void { foreach ($names as $name) { diff --git a/tests/PhpGenerator/ClassType.add.phpt b/tests/PhpGenerator/ClassType.add.phpt new file mode 100644 index 00000000..93f101e9 --- /dev/null +++ b/tests/PhpGenerator/ClassType.add.phpt @@ -0,0 +1,25 @@ +add(new stdClass); +}, Nette\InvalidArgumentException::class, 'Argument must be Method|Property|Constant.'); + + +$class = (new ClassType('Example')) + ->add($method = new Nette\PhpGenerator\Method('getHandle')) + ->add($property = new Nette\PhpGenerator\Property('handle')) + ->add($const = new Nette\PhpGenerator\Constant('ROLE')); + +Assert::same(['getHandle' => $method], $class->getMethods()); +Assert::same(['handle' => $property], $class->getProperties()); +Assert::same(['ROLE' => $const], $class->getConstants());