Skip to content

Commit e6ca48b

Browse files
committed
added NameAware::cloneWithName()
1 parent bc3b9cf commit e6ca48b

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

readme.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,14 @@ $class = (new Nette\PhpGenerator\ClassType('Demo'))
168168
->addMember($const);
169169
```
170170

171+
You can clone existing methods, properties and constants with a different name using `cloneWithName()`:
172+
173+
```php
174+
$methodCount = $class->getMethod('count');
175+
$methodRecount = $methodCount->cloneWithName('recount');
176+
$class->addMember($methodRecount);
177+
```
178+
171179
Tabs versus spaces
172180
------------------
173181

src/PhpGenerator/Traits/NameAware.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,4 +34,19 @@ public function getName(): string
3434
{
3535
return $this->name;
3636
}
37+
38+
39+
/**
40+
* Returns clone with a different name.
41+
* @return static
42+
*/
43+
public function cloneWithName(string $name): self
44+
{
45+
if (!Nette\PhpGenerator\Helpers::isIdentifier($name)) {
46+
throw new Nette\InvalidArgumentException("Value '$name' is not valid name.");
47+
}
48+
$dolly = clone $this;
49+
$dolly->name = $name;
50+
return $dolly;
51+
}
3752
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Nette\PhpGenerator\ClassType;
6+
use Tester\Assert;
7+
8+
9+
require __DIR__ . '/../bootstrap.php';
10+
11+
12+
$class = (new ClassType('Example'))
13+
->addMember($method = new Nette\PhpGenerator\Method('first'))
14+
->addMember($property = new Nette\PhpGenerator\Property('first'))
15+
->addMember($const = new Nette\PhpGenerator\Constant('FIRST'))
16+
->addMember($newMethod = $method->cloneWithName('second'))
17+
->addMember($newProperty = $property->cloneWithName('second'))
18+
->addMember($newConst = $const->cloneWithName('SECOND'));
19+
20+
Assert::same('first', $method->getName());
21+
Assert::same('second', $newMethod->getName());
22+
Assert::same('first', $property->getName());
23+
Assert::same('second', $newProperty->getName());
24+
Assert::same('FIRST', $const->getName());
25+
Assert::same('SECOND', $newConst->getName());
26+
27+
28+
Assert::exception(function () {
29+
$method = new Nette\PhpGenerator\Method('first');
30+
$method->cloneWithName('');
31+
}, Nette\InvalidArgumentException::class);

0 commit comments

Comments
 (0)