Function.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. class PHPParser_Builder_Function extends PHPParser_BuilderAbstract
  3. {
  4. protected $name;
  5. protected $returnByRef;
  6. protected $params;
  7. protected $stmts;
  8. /**
  9. * Creates a function builder.
  10. *
  11. * @param string $name Name of the function
  12. */
  13. public function __construct($name) {
  14. $this->name = $name;
  15. $this->returnByRef = false;
  16. $this->params = array();
  17. $this->stmts = array();
  18. }
  19. /**
  20. * Make the function return by reference.
  21. *
  22. * @return PHPParser_Builder_Function The builder instance (for fluid interface)
  23. */
  24. public function makeReturnByRef() {
  25. $this->returnByRef = true;
  26. return $this;
  27. }
  28. /**
  29. * Adds a parameter.
  30. *
  31. * @param PHPParser_Node_Param|PHPParser_Builder_Param $param The parameter to add
  32. *
  33. * @return PHPParser_Builder_Function The builder instance (for fluid interface)
  34. */
  35. public function addParam($param) {
  36. $param = $this->normalizeNode($param);
  37. if (!$param instanceof PHPParser_Node_Param) {
  38. throw new LogicException(sprintf('Expected parameter node, got "%s"', $param->getType()));
  39. }
  40. $this->params[] = $param;
  41. return $this;
  42. }
  43. /**
  44. * Adds multiple parameters.
  45. *
  46. * @param array $params The parameters to add
  47. *
  48. * @return PHPParser_Builder_Function The builder instance (for fluid interface)
  49. */
  50. public function addParams(array $params) {
  51. foreach ($params as $param) {
  52. $this->addParam($param);
  53. }
  54. return $this;
  55. }
  56. /**
  57. * Adds a statement.
  58. *
  59. * @param PHPParser_Node|PHPParser_Builder $stmt The statement to add
  60. *
  61. * @return PHPParser_Builder_Function The builder instance (for fluid interface)
  62. */
  63. public function addStmt($stmt) {
  64. $this->stmts[] = $this->normalizeNode($stmt);
  65. return $this;
  66. }
  67. /**
  68. * Adds multiple statements.
  69. *
  70. * @param array $stmts The statements to add
  71. *
  72. * @return PHPParser_Builder_Function The builder instance (for fluid interface)
  73. */
  74. public function addStmts(array $stmts) {
  75. foreach ($stmts as $stmt) {
  76. $this->addStmt($stmt);
  77. }
  78. return $this;
  79. }
  80. /**
  81. * Returns the built function node.
  82. *
  83. * @return PHPParser_Node_Stmt_Function The built function node
  84. */
  85. public function getNode() {
  86. return new PHPParser_Node_Stmt_Function($this->name, array(
  87. 'byRef' => $this->returnByRef,
  88. 'params' => $this->params,
  89. 'stmts' => $this->stmts,
  90. ));
  91. }
  92. }