diff --git a/readme.md b/readme.md index 9b885e97..eda3e43d 100644 --- a/readme.md +++ b/readme.md @@ -402,6 +402,7 @@ class Demo implements A } ``` +TODO: import() Generate using Reflection ------------------------- 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..9cfaa05c --- /dev/null +++ b/tests/PhpGenerator/ClassType.add.phpt @@ -0,0 +1,26 @@ +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());