FunctionTest.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. namespace PhpParser\Builder;
  3. use PhpParser\Comment;
  4. use PhpParser\Node;
  5. use PhpParser\Node\Expr\Print_;
  6. use PhpParser\Node\Scalar\String_;
  7. use PhpParser\Node\Stmt;
  8. class FunctionTest extends \PHPUnit_Framework_TestCase
  9. {
  10. public function createFunctionBuilder($name) {
  11. return new Function_($name);
  12. }
  13. public function testReturnByRef() {
  14. $node = $this->createFunctionBuilder('test')
  15. ->makeReturnByRef()
  16. ->getNode()
  17. ;
  18. $this->assertEquals(
  19. new Stmt\Function_('test', array(
  20. 'byRef' => true
  21. )),
  22. $node
  23. );
  24. }
  25. public function testParams() {
  26. $param1 = new Node\Param('test1');
  27. $param2 = new Node\Param('test2');
  28. $param3 = new Node\Param('test3');
  29. $node = $this->createFunctionBuilder('test')
  30. ->addParam($param1)
  31. ->addParams(array($param2, $param3))
  32. ->getNode()
  33. ;
  34. $this->assertEquals(
  35. new Stmt\Function_('test', array(
  36. 'params' => array($param1, $param2, $param3)
  37. )),
  38. $node
  39. );
  40. }
  41. public function testStmts() {
  42. $stmt1 = new Print_(new String_('test1'));
  43. $stmt2 = new Print_(new String_('test2'));
  44. $stmt3 = new Print_(new String_('test3'));
  45. $node = $this->createFunctionBuilder('test')
  46. ->addStmt($stmt1)
  47. ->addStmts(array($stmt2, $stmt3))
  48. ->getNode()
  49. ;
  50. $this->assertEquals(
  51. new Stmt\Function_('test', array(
  52. 'stmts' => array($stmt1, $stmt2, $stmt3)
  53. )),
  54. $node
  55. );
  56. }
  57. public function testDocComment() {
  58. $node = $this->createFunctionBuilder('test')
  59. ->setDocComment('/** Test */')
  60. ->getNode();
  61. $this->assertEquals(new Stmt\Function_('test', array(), array(
  62. 'comments' => array(new Comment\Doc('/** Test */'))
  63. )), $node);
  64. }
  65. public function testReturnType() {
  66. $node = $this->createFunctionBuilder('test')
  67. ->setReturnType('void')
  68. ->getNode();
  69. $this->assertEquals(new Stmt\Function_('test', array(
  70. 'returnType' => 'void'
  71. ), array()), $node);
  72. }
  73. /**
  74. * @expectedException \LogicException
  75. * @expectedExceptionMessage void type cannot be nullable
  76. */
  77. public function testInvalidNullableVoidType() {
  78. $this->createFunctionBuilder('test')->setReturnType('?void');
  79. }
  80. /**
  81. * @expectedException \LogicException
  82. * @expectedExceptionMessage Expected parameter node, got "Name"
  83. */
  84. public function testInvalidParamError() {
  85. $this->createFunctionBuilder('test')
  86. ->addParam(new Node\Name('foo'))
  87. ;
  88. }
  89. }