Skip to content

Commit

Permalink
added NameAware::cloneWithName()
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Aug 9, 2018
1 parent ceb0834 commit ab39e29
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
8 changes: 8 additions & 0 deletions readme.md
Expand Up @@ -168,6 +168,14 @@ $class = (new Nette\PhpGenerator\ClassType('Demo'))
->addMember($const);
```

You can clone existing methods, properties and constants with a different name:

```php
$methodCount = $class->getMethod('count');
$methodRecount = $methodCount->cloneWithName('recount');
$class->addMember($methodRecount);
```

Tabs versus spaces
------------------

Expand Down
15 changes: 15 additions & 0 deletions src/PhpGenerator/Traits/NameAware.php
Expand Up @@ -34,4 +34,19 @@ public function getName(): string
{
return $this->name;
}


/**
* Returns clone with a different name.
* @return static
*/
public function cloneWithName(string $name): self
{
if (!Nette\PhpGenerator\Helpers::isIdentifier($name)) {
throw new Nette\InvalidArgumentException("Value '$name' is not valid name.");
}
$dolly = clone $this;
$dolly->name = $name;
return $dolly;
}
}
25 changes: 25 additions & 0 deletions tests/PhpGenerator/NameAware.cloneWithName.phpt
@@ -0,0 +1,25 @@
<?php

declare(strict_types=1);

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


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


$class = (new ClassType('Example'))
->addMember($method = new Nette\PhpGenerator\Method('first'))
->addMember($property = new Nette\PhpGenerator\Property('first'))
->addMember($const = new Nette\PhpGenerator\Constant('FIRST'))
->addMember($newMethod = $method->cloneWithName('second'))
->addMember($newProperty = $property->cloneWithName('second'))
->addMember($newConst = $const->cloneWithName('SECOND'));

Assert::same('first', $method->getName());
Assert::same('second', $newMethod->getName());
Assert::same('first', $property->getName());
Assert::same('second', $newProperty->getName());
Assert::same('FIRST', $const->getName());
Assert::same('SECOND', $newConst->getName());

0 comments on commit ab39e29

Please sign in to comment.