diff --git a/readme.md b/readme.md index aba0091c..d5f877fc 100644 --- a/readme.md +++ b/readme.md @@ -153,6 +153,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')) + ->addMember($method) + ->addMember($property) + ->addMember($const); +``` + Tabs versus spaces ------------------ diff --git a/src/PhpGenerator/ClassType.php b/src/PhpGenerator/ClassType.php index 658a5a68..8c7c0939 100644 --- a/src/PhpGenerator/ClassType.php +++ b/src/PhpGenerator/ClassType.php @@ -313,6 +313,32 @@ public function addTrait(string $name, array $resolutions = []): self } + /** + * @param Method|Property|Constant $member + * @return static + */ + public function addMember($member): self + { + if ($member instanceof Method) { + if ($this->type === self::TYPE_INTERFACE) { + $member->setBody(null); + } + $this->methods[$member->getName()] = $member->setNamespace($this->namespace); + + } 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; + } + + /** * @param Constant[]|mixed[] $consts * @return static diff --git a/tests/PhpGenerator/ClassType.addMember.phpt b/tests/PhpGenerator/ClassType.addMember.phpt new file mode 100644 index 00000000..e1a7905f --- /dev/null +++ b/tests/PhpGenerator/ClassType.addMember.phpt @@ -0,0 +1,33 @@ +addMember(new stdClass); +}, Nette\InvalidArgumentException::class, 'Argument must be Method|Property|Constant.'); + + +$class = (new ClassType('Example')) + ->addMember($method = new Nette\PhpGenerator\Method('getHandle')) + ->addMember($property = new Nette\PhpGenerator\Property('handle')) + ->addMember($const = new Nette\PhpGenerator\Constant('ROLE')); + +Assert::same(['getHandle' => $method], $class->getMethods()); +Assert::same(['handle' => $property], $class->getProperties()); +Assert::same(['ROLE' => $const], $class->getConstants()); +Assert::same('', $method->getBody()); + + +$class = (new ClassType('Example')) + ->setType('interface') + ->addMember($method = new Nette\PhpGenerator\Method('getHandle')); + +Assert::null($method->getBody());