ClassConst.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. declare(strict_types=1);
  3. namespace PhpParser\Builder;
  4. use PhpParser;
  5. use PhpParser\BuilderHelpers;
  6. use PhpParser\Node\Const_;
  7. use PhpParser\Node\Identifier;
  8. use PhpParser\Node\Stmt;
  9. class ClassConst implements PhpParser\Builder
  10. {
  11. protected $flags = 0;
  12. protected $attributes = [];
  13. protected $constants = [];
  14. /**
  15. * Creates a class constant builder
  16. *
  17. * @param string|Identifier $name Name
  18. * @param Node\Expr|bool|null|int|float|string|array $value Value
  19. */
  20. public function __construct($name, $value) {
  21. $this->constants = [new Const_($name, BuilderHelpers::normalizeValue($value))];
  22. }
  23. /**
  24. * Add another constant to const group
  25. *
  26. * @param string|Identifier $name Name
  27. * @param Node\Expr|bool|null|int|float|string|array $value Value
  28. *
  29. * @return $this The builder instance (for fluid interface)
  30. */
  31. public function addConst($name, $value) {
  32. $this->constants[] = new Const_($name, BuilderHelpers::normalizeValue($value));
  33. return $this;
  34. }
  35. /**
  36. * Makes the constant public.
  37. *
  38. * @return $this The builder instance (for fluid interface)
  39. */
  40. public function makePublic() {
  41. $this->flags = BuilderHelpers::addModifier($this->flags, Stmt\Class_::MODIFIER_PUBLIC);
  42. return $this;
  43. }
  44. /**
  45. * Makes the constant protected.
  46. *
  47. * @return $this The builder instance (for fluid interface)
  48. */
  49. public function makeProtected() {
  50. $this->flags = BuilderHelpers::addModifier($this->flags, Stmt\Class_::MODIFIER_PROTECTED);
  51. return $this;
  52. }
  53. /**
  54. * Makes the constant private.
  55. *
  56. * @return $this The builder instance (for fluid interface)
  57. */
  58. public function makePrivate() {
  59. $this->flags = BuilderHelpers::addModifier($this->flags, Stmt\Class_::MODIFIER_PRIVATE);
  60. return $this;
  61. }
  62. /**
  63. * Sets doc comment for the constant.
  64. *
  65. * @param PhpParser\Comment\Doc|string $docComment Doc comment to set
  66. *
  67. * @return $this The builder instance (for fluid interface)
  68. */
  69. public function setDocComment($docComment) {
  70. $this->attributes = [
  71. 'comments' => [BuilderHelpers::normalizeDocComment($docComment)]
  72. ];
  73. return $this;
  74. }
  75. /**
  76. * Returns the built class node.
  77. *
  78. * @return Stmt\ClassConst The built constant node
  79. */
  80. public function getNode(): PhpParser\Node {
  81. return new Stmt\ClassConst(
  82. $this->constants,
  83. $this->flags,
  84. $this->attributes
  85. );
  86. }
  87. }