|
3 | 3 | namespace PhpParser\Node;
|
4 | 4 |
|
5 | 5 | use PhpParser\Modifiers;
|
| 6 | +use PhpParser\Node\Expr\Assign; |
| 7 | +use PhpParser\Node\Expr\PropertyFetch; |
6 | 8 | use PhpParser\Node\Expr\Variable;
|
| 9 | +use PhpParser\Node\Scalar\Int_; |
7 | 10 | use PhpParser\Node\Stmt\Expression;
|
8 | 11 | use PhpParser\Node\Stmt\Return_;
|
| 12 | +use PhpParser\ParserFactory; |
| 13 | +use PhpParser\PrettyPrinter\Standard; |
9 | 14 |
|
10 | 15 | class PropertyHookTest extends \PHPUnit\Framework\TestCase {
|
11 | 16 | /**
|
@@ -40,17 +45,45 @@ public function testGetStmts(): void {
|
40 | 45 | $get = new PropertyHook('get', $expr);
|
41 | 46 | $this->assertEquals([new Return_($expr)], $get->getStmts());
|
42 | 47 |
|
43 |
| - // TODO: This is incorrect. |
44 |
| - $set = new PropertyHook('set', $expr); |
45 |
| - $this->assertEquals([new Expression($expr)], $set->getStmts()); |
| 48 | + $set = new PropertyHook('set', $expr, [], ['propertyName' => 'abc']); |
| 49 | + $this->assertEquals([ |
| 50 | + new Expression(new Assign(new PropertyFetch(new Variable('this'), 'abc'), $expr)) |
| 51 | + ], $set->getStmts()); |
| 52 | + } |
| 53 | + |
| 54 | + public function testGetStmtsSetHookFromParser(): void { |
| 55 | + $parser = (new ParserFactory())->createForNewestSupportedVersion(); |
| 56 | + $prettyPrinter = new Standard(); |
| 57 | + $stmts = $parser->parse(<<<'CODE' |
| 58 | + <?php |
| 59 | + class Test { |
| 60 | + public $prop1 { set => 123; } |
| 61 | +
|
| 62 | + public function __construct(public $prop2 { set => 456; }) {} |
| 63 | + } |
| 64 | + CODE); |
| 65 | + |
| 66 | + $hook1 = $stmts[0]->stmts[0]->hooks[0]; |
| 67 | + $this->assertEquals('$this->prop1 = 123;', $prettyPrinter->prettyPrint($hook1->getStmts())); |
| 68 | + |
| 69 | + $hook2 = $stmts[0]->stmts[1]->params[0]->hooks[0]; |
| 70 | + $this->assertEquals('$this->prop2 = 456;', $prettyPrinter->prettyPrint($hook2->getStmts())); |
46 | 71 | }
|
47 | 72 |
|
48 |
| - public function testSetStmtsUnknownHook(): void { |
| 73 | + public function testGetStmtsUnknownHook(): void { |
49 | 74 | $expr = new Variable('test');
|
50 |
| - $get = new PropertyHook('foobar', $expr); |
| 75 | + $hook = new PropertyHook('foobar', $expr); |
51 | 76 |
|
52 | 77 | $this->expectException(\LogicException::class);
|
53 | 78 | $this->expectExceptionMessage('Unknown property hook "foobar"');
|
54 |
| - $get->getStmts(); |
| 79 | + $hook->getStmts(); |
| 80 | + } |
| 81 | + |
| 82 | + public function testGetStmtsSetHookWithoutPropertyName(): void { |
| 83 | + $expr = new Variable('test'); |
| 84 | + $set = new PropertyHook('set', $expr); |
| 85 | + $this->expectException(\LogicException::class); |
| 86 | + $this->expectExceptionMessage('Can only use getStmts() on a "set" hook if the "propertyName" attribute is set'); |
| 87 | + $set->getStmts(); |
55 | 88 | }
|
56 | 89 | }
|
0 commit comments