BuilderFactoryTest.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. <?php declare(strict_types=1);
  2. namespace PhpParser;
  3. use PhpParser\Node\Arg;
  4. use PhpParser\Node\Expr;
  5. use PhpParser\Node\Expr\BinaryOp\Concat;
  6. use PhpParser\Node\Identifier;
  7. use PhpParser\Node\Name;
  8. use PhpParser\Node\Scalar\LNumber;
  9. use PhpParser\Node\Scalar\String_;
  10. class BuilderFactoryTest extends \PHPUnit\Framework\TestCase
  11. {
  12. /**
  13. * @dataProvider provideTestFactory
  14. */
  15. public function testFactory($methodName, $className) {
  16. $factory = new BuilderFactory;
  17. $this->assertInstanceOf($className, $factory->$methodName('test'));
  18. }
  19. public function provideTestFactory() {
  20. return [
  21. ['namespace', Builder\Namespace_::class],
  22. ['class', Builder\Class_::class],
  23. ['interface', Builder\Interface_::class],
  24. ['trait', Builder\Trait_::class],
  25. ['method', Builder\Method::class],
  26. ['function', Builder\Function_::class],
  27. ['property', Builder\Property::class],
  28. ['param', Builder\Param::class],
  29. ['use', Builder\Use_::class],
  30. ['useFunction', Builder\Use_::class],
  31. ['useConst', Builder\Use_::class],
  32. ];
  33. }
  34. public function testVal() {
  35. // This method is a wrapper around BuilderHelpers::normalizeValue(),
  36. // which is already tested elsewhere
  37. $factory = new BuilderFactory();
  38. $this->assertEquals(
  39. new String_("foo"),
  40. $factory->val("foo")
  41. );
  42. }
  43. public function testConcat() {
  44. $factory = new BuilderFactory();
  45. $varA = new Expr\Variable('a');
  46. $varB = new Expr\Variable('b');
  47. $varC = new Expr\Variable('c');
  48. $this->assertEquals(
  49. new Concat($varA, $varB),
  50. $factory->concat($varA, $varB)
  51. );
  52. $this->assertEquals(
  53. new Concat(new Concat($varA, $varB), $varC),
  54. $factory->concat($varA, $varB, $varC)
  55. );
  56. $this->assertEquals(
  57. new Concat(new Concat(new String_("a"), $varB), new String_("c")),
  58. $factory->concat("a", $varB, "c")
  59. );
  60. }
  61. public function testConcatOneError() {
  62. $this->expectException(\LogicException::class);
  63. $this->expectExceptionMessage('Expected at least two expressions');
  64. (new BuilderFactory())->concat("a");
  65. }
  66. public function testConcatInvalidExpr() {
  67. $this->expectException(\LogicException::class);
  68. $this->expectExceptionMessage('Expected string or Expr');
  69. (new BuilderFactory())->concat("a", 42);
  70. }
  71. public function testArgs() {
  72. $factory = new BuilderFactory();
  73. $unpack = new Arg(new Expr\Variable('c'), false, true);
  74. $this->assertEquals(
  75. [
  76. new Arg(new Expr\Variable('a')),
  77. new Arg(new String_('b')),
  78. $unpack
  79. ],
  80. $factory->args([new Expr\Variable('a'), 'b', $unpack])
  81. );
  82. }
  83. public function testCalls() {
  84. $factory = new BuilderFactory();
  85. // Simple function call
  86. $this->assertEquals(
  87. new Expr\FuncCall(
  88. new Name('var_dump'),
  89. [new Arg(new String_('str'))]
  90. ),
  91. $factory->funcCall('var_dump', ['str'])
  92. );
  93. // Dynamic function call
  94. $this->assertEquals(
  95. new Expr\FuncCall(new Expr\Variable('fn')),
  96. $factory->funcCall(new Expr\Variable('fn'))
  97. );
  98. // Simple method call
  99. $this->assertEquals(
  100. new Expr\MethodCall(
  101. new Expr\Variable('obj'),
  102. new Identifier('method'),
  103. [new Arg(new LNumber(42))]
  104. ),
  105. $factory->methodCall(new Expr\Variable('obj'), 'method', [42])
  106. );
  107. // Explicitly pass Identifier node
  108. $this->assertEquals(
  109. new Expr\MethodCall(
  110. new Expr\Variable('obj'),
  111. new Identifier('method')
  112. ),
  113. $factory->methodCall(new Expr\Variable('obj'), new Identifier('method'))
  114. );
  115. // Dynamic method call
  116. $this->assertEquals(
  117. new Expr\MethodCall(
  118. new Expr\Variable('obj'),
  119. new Expr\Variable('method')
  120. ),
  121. $factory->methodCall(new Expr\Variable('obj'), new Expr\Variable('method'))
  122. );
  123. // Simple static method call
  124. $this->assertEquals(
  125. new Expr\StaticCall(
  126. new Name\FullyQualified('Foo'),
  127. new Identifier('bar'),
  128. [new Arg(new Expr\Variable('baz'))]
  129. ),
  130. $factory->staticCall('\Foo', 'bar', [new Expr\Variable('baz')])
  131. );
  132. // Dynamic static method call
  133. $this->assertEquals(
  134. new Expr\StaticCall(
  135. new Expr\Variable('foo'),
  136. new Expr\Variable('bar')
  137. ),
  138. $factory->staticCall(new Expr\Variable('foo'), new Expr\Variable('bar'))
  139. );
  140. // Simple new call
  141. $this->assertEquals(
  142. new Expr\New_(new Name\FullyQualified('stdClass')),
  143. $factory->new('\stdClass')
  144. );
  145. // Dynamic new call
  146. $this->assertEquals(
  147. new Expr\New_(
  148. new Expr\Variable('foo'),
  149. [new Arg(new String_('bar'))]
  150. ),
  151. $factory->new(new Expr\Variable('foo'), ['bar'])
  152. );
  153. }
  154. public function testConstFetches() {
  155. $factory = new BuilderFactory();
  156. $this->assertEquals(
  157. new Expr\ConstFetch(new Name('FOO')),
  158. $factory->constFetch('FOO')
  159. );
  160. $this->assertEquals(
  161. new Expr\ClassConstFetch(new Name('Foo'), new Identifier('BAR')),
  162. $factory->classConstFetch('Foo', 'BAR')
  163. );
  164. $this->assertEquals(
  165. new Expr\ClassConstFetch(new Expr\Variable('foo'), new Identifier('BAR')),
  166. $factory->classConstFetch(new Expr\Variable('foo'), 'BAR')
  167. );
  168. }
  169. public function testVar() {
  170. $factory = new BuilderFactory();
  171. $this->assertEquals(
  172. new Expr\Variable("foo"),
  173. $factory->var("foo")
  174. );
  175. $this->assertEquals(
  176. new Expr\Variable(new Expr\Variable("foo")),
  177. $factory->var($factory->var("foo"))
  178. );
  179. }
  180. public function testPropertyFetch() {
  181. $f = new BuilderFactory();
  182. $this->assertEquals(
  183. new Expr\PropertyFetch(new Expr\Variable('foo'), 'bar'),
  184. $f->propertyFetch($f->var('foo'), 'bar')
  185. );
  186. $this->assertEquals(
  187. new Expr\PropertyFetch(new Expr\Variable('foo'), 'bar'),
  188. $f->propertyFetch($f->var('foo'), new Identifier('bar'))
  189. );
  190. $this->assertEquals(
  191. new Expr\PropertyFetch(new Expr\Variable('foo'), new Expr\Variable('bar')),
  192. $f->propertyFetch($f->var('foo'), $f->var('bar'))
  193. );
  194. }
  195. public function testInvalidIdentifier() {
  196. $this->expectException(\LogicException::class);
  197. $this->expectExceptionMessage('Expected string or instance of Node\Identifier');
  198. (new BuilderFactory())->classConstFetch('Foo', new Expr\Variable('foo'));
  199. }
  200. public function testInvalidIdentifierOrExpr() {
  201. $this->expectException(\LogicException::class);
  202. $this->expectExceptionMessage('Expected string or instance of Node\Identifier or Node\Expr');
  203. (new BuilderFactory())->staticCall('Foo', new Name('bar'));
  204. }
  205. public function testInvalidNameOrExpr() {
  206. $this->expectException(\LogicException::class);
  207. $this->expectExceptionMessage('Name must be a string or an instance of Node\Name or Node\Expr');
  208. (new BuilderFactory())->funcCall(new Node\Stmt\Return_());
  209. }
  210. public function testInvalidVar() {
  211. $this->expectException(\LogicException::class);
  212. $this->expectExceptionMessage('Variable name must be string or Expr');
  213. (new BuilderFactory())->var(new Node\Stmt\Return_());
  214. }
  215. public function testIntegration() {
  216. $factory = new BuilderFactory;
  217. $node = $factory->namespace('Name\Space')
  218. ->addStmt($factory->use('Foo\Bar\SomeOtherClass'))
  219. ->addStmt($factory->use('Foo\Bar')->as('A'))
  220. ->addStmt($factory->useFunction('strlen'))
  221. ->addStmt($factory->useConst('PHP_VERSION'))
  222. ->addStmt($factory
  223. ->class('SomeClass')
  224. ->extend('SomeOtherClass')
  225. ->implement('A\Few', '\Interfaces')
  226. ->makeAbstract()
  227. ->addStmt($factory->useTrait('FirstTrait'))
  228. ->addStmt($factory->useTrait('SecondTrait', 'ThirdTrait')
  229. ->and('AnotherTrait')
  230. ->with($factory->traitUseAdaptation('foo')->as('bar'))
  231. ->with($factory->traitUseAdaptation('AnotherTrait', 'baz')->as('test'))
  232. ->with($factory->traitUseAdaptation('AnotherTrait', 'func')->insteadof('SecondTrait')))
  233. ->addStmt($factory->method('firstMethod'))
  234. ->addStmt($factory->method('someMethod')
  235. ->makePublic()
  236. ->makeAbstract()
  237. ->addParam($factory->param('someParam')->setType('SomeClass'))
  238. ->setDocComment('/**
  239. * This method does something.
  240. *
  241. * @param SomeClass And takes a parameter
  242. */'))
  243. ->addStmt($factory->method('anotherMethod')
  244. ->makeProtected()
  245. ->addParam($factory->param('someParam')->setDefault('test'))
  246. ->addStmt(new Expr\Print_(new Expr\Variable('someParam'))))
  247. ->addStmt($factory->property('someProperty')->makeProtected())
  248. ->addStmt($factory->property('anotherProperty')
  249. ->makePrivate()
  250. ->setDefault([1, 2, 3])))
  251. ->getNode()
  252. ;
  253. $expected = <<<'EOC'
  254. <?php
  255. namespace Name\Space;
  256. use Foo\Bar\SomeOtherClass;
  257. use Foo\Bar as A;
  258. use function strlen;
  259. use const PHP_VERSION;
  260. abstract class SomeClass extends SomeOtherClass implements A\Few, \Interfaces
  261. {
  262. use FirstTrait;
  263. use SecondTrait, ThirdTrait, AnotherTrait {
  264. foo as bar;
  265. AnotherTrait::baz as test;
  266. AnotherTrait::func insteadof SecondTrait;
  267. }
  268. protected $someProperty;
  269. private $anotherProperty = array(1, 2, 3);
  270. function firstMethod()
  271. {
  272. }
  273. /**
  274. * This method does something.
  275. *
  276. * @param SomeClass And takes a parameter
  277. */
  278. public abstract function someMethod(SomeClass $someParam);
  279. protected function anotherMethod($someParam = 'test')
  280. {
  281. print $someParam;
  282. }
  283. }
  284. EOC;
  285. $stmts = [$node];
  286. $prettyPrinter = new PrettyPrinter\Standard();
  287. $generated = $prettyPrinter->prettyPrintFile($stmts);
  288. $this->assertEquals(
  289. str_replace("\r\n", "\n", $expected),
  290. str_replace("\r\n", "\n", $generated)
  291. );
  292. }
  293. }