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 fd6ea6a commit 61ab4cf
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
13 changes: 13 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
------------------

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
25 changes: 25 additions & 0 deletions tests/PhpGenerator/ClassType.add.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

declare(strict_types=1);

use Nette\PhpGenerator\ClassType;
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 61ab4cf

Please sign in to comment.