Param.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php declare(strict_types=1);
  2. namespace PhpParser\Builder;
  3. use PhpParser;
  4. use PhpParser\BuilderHelpers;
  5. use PhpParser\Node;
  6. class Param implements PhpParser\Builder
  7. {
  8. protected $name;
  9. protected $default = null;
  10. /** @var Node\Identifier|Node\Name|Node\NullableType|null */
  11. protected $type = null;
  12. protected $byRef = false;
  13. protected $variadic = false;
  14. /**
  15. * Creates a parameter builder.
  16. *
  17. * @param string $name Name of the parameter
  18. */
  19. public function __construct(string $name) {
  20. $this->name = $name;
  21. }
  22. /**
  23. * Sets default value for the parameter.
  24. *
  25. * @param mixed $value Default value to use
  26. *
  27. * @return $this The builder instance (for fluid interface)
  28. */
  29. public function setDefault($value) {
  30. $this->default = BuilderHelpers::normalizeValue($value);
  31. return $this;
  32. }
  33. /**
  34. * Sets type for the parameter.
  35. *
  36. * @param string|Node\Name|Node\NullableType|Node\UnionType $type Parameter type
  37. *
  38. * @return $this The builder instance (for fluid interface)
  39. */
  40. public function setType($type) {
  41. $this->type = BuilderHelpers::normalizeType($type);
  42. if ($this->type == 'void') {
  43. throw new \LogicException('Parameter type cannot be void');
  44. }
  45. return $this;
  46. }
  47. /**
  48. * Sets type for the parameter.
  49. *
  50. * @param string|Node\Name|Node\NullableType|Node\UnionType $type Parameter type
  51. *
  52. * @return $this The builder instance (for fluid interface)
  53. *
  54. * @deprecated Use setType() instead
  55. */
  56. public function setTypeHint($type) {
  57. return $this->setType($type);
  58. }
  59. /**
  60. * Make the parameter accept the value by reference.
  61. *
  62. * @return $this The builder instance (for fluid interface)
  63. */
  64. public function makeByRef() {
  65. $this->byRef = true;
  66. return $this;
  67. }
  68. /**
  69. * Make the parameter variadic
  70. *
  71. * @return $this The builder instance (for fluid interface)
  72. */
  73. public function makeVariadic() {
  74. $this->variadic = true;
  75. return $this;
  76. }
  77. /**
  78. * Returns the built parameter node.
  79. *
  80. * @return Node\Param The built parameter node
  81. */
  82. public function getNode() : Node {
  83. return new Node\Param(
  84. new Node\Expr\Variable($this->name),
  85. $this->default, $this->type, $this->byRef, $this->variadic
  86. );
  87. }
  88. }