From b862de1f5bdb1db0b9ce0aad97409ac5c78710c6 Mon Sep 17 00:00:00 2001 From: Nikita Popov Date: Sat, 11 Jul 2015 22:31:45 +0200 Subject: [PATCH] Support properties in trait builder --- lib/PhpParser/Builder/Trait_.php | 14 ++++++++++---- test/PhpParser/Builder/TraitTest.php | 6 +++++- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/lib/PhpParser/Builder/Trait_.php b/lib/PhpParser/Builder/Trait_.php index a1953ce..9722e35 100644 --- a/lib/PhpParser/Builder/Trait_.php +++ b/lib/PhpParser/Builder/Trait_.php @@ -9,6 +9,7 @@ use PhpParser\Node\Stmt; class Trait_ extends Declaration { protected $name; + protected $properties = array(); protected $methods = array(); /** @@ -29,12 +30,15 @@ class Trait_ extends Declaration */ public function addStmt($stmt) { $stmt = $this->normalizeNode($stmt); - if (!$stmt instanceof Stmt\ClassMethod) { + + if ($stmt instanceof Stmt\Property) { + $this->properties[] = $stmt; + } else if ($stmt instanceof Stmt\ClassMethod) { + $this->methods[] = $stmt; + } else { throw new \LogicException(sprintf('Unexpected node of type "%s"', $stmt->getType())); } - $this->methods[] = $stmt; - return $this; } @@ -44,6 +48,8 @@ class Trait_ extends Declaration * @return Stmt\Trait_ The built interface node */ public function getNode() { - return new Stmt\Trait_($this->name, $this->methods, $this->attributes); + return new Stmt\Trait_( + $this->name, array_merge($this->properties, $this->methods), $this->attributes + ); } } diff --git a/test/PhpParser/Builder/TraitTest.php b/test/PhpParser/Builder/TraitTest.php index d52185c..a6d69ad 100644 --- a/test/PhpParser/Builder/TraitTest.php +++ b/test/PhpParser/Builder/TraitTest.php @@ -17,13 +17,17 @@ class TraitTest extends \PHPUnit_Framework_TestCase $method1 = new Stmt\ClassMethod('test1'); $method2 = new Stmt\ClassMethod('test2'); $method3 = new Stmt\ClassMethod('test3'); + $prop = new Stmt\Property(Stmt\Class_::MODIFIER_PUBLIC, array( + new Stmt\PropertyProperty('test') + )); $trait = $this->createTraitBuilder('TestTrait') ->setDocComment('/** Nice trait */') ->addStmt($method1) ->addStmts(array($method2, $method3)) + ->addStmt($prop) ->getNode(); $this->assertEquals(new Stmt\Trait_('TestTrait', array( - $method1, $method2, $method3 + $prop, $method1, $method2, $method3 ), array( 'comments' => array( new Comment\Doc('/** Nice trait */')