Skip to content

Commit

Permalink
added ClassType::add() [Closes #35]
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Aug 6, 2018
1 parent bf6320f commit 1787a10
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
1 change: 1 addition & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,7 @@ class Demo implements A
}
```

TODO: import()

Generate using Reflection
-------------------------
Expand Down
26 changes: 26 additions & 0 deletions src/PhpGenerator/ClassType.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
26 changes: 26 additions & 0 deletions tests/PhpGenerator/ClassType.add.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

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


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


Assert::exception(function () {
(new ClassType('Example'))
->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());

0 comments on commit 1787a10

Please sign in to comment.