1 <?php declare(strict_types=1);
3 namespace PhpParser\Builder;
7 use PhpParser\Node\Name;
8 use PhpParser\Node\Stmt;
9 use PHPUnit\Framework\TestCase;
11 class ClassTest extends TestCase
13 protected function createClassBuilder($class) {
14 return new Class_($class);
17 public function testExtendsImplements() {
18 $node = $this->createClassBuilder('SomeLogger')
19 ->extend('BaseLogger')
20 ->implement('Namespaced\Logger', new Name('SomeInterface'))
21 ->implement('\Fully\Qualified', 'namespace\NamespaceRelative')
26 new Stmt\Class_('SomeLogger', [
27 'extends' => new Name('BaseLogger'),
29 new Name('Namespaced\Logger'),
30 new Name('SomeInterface'),
31 new Name\FullyQualified('Fully\Qualified'),
32 new Name\Relative('NamespaceRelative'),
39 public function testAbstract() {
40 $node = $this->createClassBuilder('Test')
46 new Stmt\Class_('Test', [
47 'flags' => Stmt\Class_::MODIFIER_ABSTRACT
53 public function testFinal() {
54 $node = $this->createClassBuilder('Test')
60 new Stmt\Class_('Test', [
61 'flags' => Stmt\Class_::MODIFIER_FINAL
67 public function testStatementOrder() {
68 $method = new Stmt\ClassMethod('testMethod');
69 $property = new Stmt\Property(
70 Stmt\Class_::MODIFIER_PUBLIC,
71 [new Stmt\PropertyProperty('testProperty')]
73 $const = new Stmt\ClassConst([
74 new Node\Const_('TEST_CONST', new Node\Scalar\String_('ABC'))
76 $use = new Stmt\TraitUse([new Name('SomeTrait')]);
78 $node = $this->createClassBuilder('Test')
81 ->addStmts([$const, $use])
86 new Stmt\Class_('Test', [
87 'stmts' => [$use, $const, $property, $method]
93 public function testDocComment() {
94 $docComment = <<<'DOC'
99 $class = $this->createClassBuilder('Test')
100 ->setDocComment($docComment)
104 new Stmt\Class_('Test', [], [
106 new Comment\Doc($docComment)
112 $class = $this->createClassBuilder('Test')
113 ->setDocComment(new Comment\Doc($docComment))
117 new Stmt\Class_('Test', [], [
119 new Comment\Doc($docComment)
126 public function testInvalidStmtError() {
127 $this->expectException(\LogicException::class);
128 $this->expectExceptionMessage('Unexpected node of type "Stmt_Echo"');
129 $this->createClassBuilder('Test')
130 ->addStmt(new Stmt\Echo_([]))
134 public function testInvalidDocComment() {
135 $this->expectException(\LogicException::class);
136 $this->expectExceptionMessage('Doc comment must be a string or an instance of PhpParser\Comment\Doc');
137 $this->createClassBuilder('Test')
138 ->setDocComment(new Comment('Test'));
141 public function testEmptyName() {
142 $this->expectException(\LogicException::class);
143 $this->expectExceptionMessage('Name cannot be empty');
144 $this->createClassBuilder('Test')
148 public function testInvalidName() {
149 $this->expectException(\LogicException::class);
150 $this->expectExceptionMessage('Name must be a string or an instance of Node\Name');
151 $this->createClassBuilder('Test')