Skip to content

Commit

Permalink
ClassType: added addMember() [Closes #35]
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Aug 29, 2018
1 parent 9b5c9e5 commit a30ffa0
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 0 deletions.
13 changes: 13 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
------------------

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

declare(strict_types=1);

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


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


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

0 comments on commit a30ffa0

Please sign in to comment.