TraitUse.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php declare(strict_types=1);
  2. namespace PhpParser\Builder;
  3. use PhpParser\Builder;
  4. use PhpParser\BuilderHelpers;
  5. use PhpParser\Node;
  6. use PhpParser\Node\Stmt;
  7. class TraitUse implements Builder
  8. {
  9. protected $traits = [];
  10. protected $adaptations = [];
  11. /**
  12. * Creates a trait use builder.
  13. *
  14. * @param Node\Name|string ...$traits Names of used traits
  15. */
  16. public function __construct(...$traits) {
  17. foreach ($traits as $trait) {
  18. $this->and($trait);
  19. }
  20. }
  21. /**
  22. * Adds used trait.
  23. *
  24. * @param Node\Name|string $trait Trait name
  25. *
  26. * @return $this The builder instance (for fluid interface)
  27. */
  28. public function and($trait) {
  29. $this->traits[] = BuilderHelpers::normalizeName($trait);
  30. return $this;
  31. }
  32. /**
  33. * Adds trait adaptation.
  34. *
  35. * @param Stmt\TraitUseAdaptation|Builder\TraitUseAdaptation $adaptation Trait adaptation
  36. *
  37. * @return $this The builder instance (for fluid interface)
  38. */
  39. public function with($adaptation) {
  40. $adaptation = BuilderHelpers::normalizeNode($adaptation);
  41. if (!$adaptation instanceof Stmt\TraitUseAdaptation) {
  42. throw new \LogicException('Adaptation must have type TraitUseAdaptation');
  43. }
  44. $this->adaptations[] = $adaptation;
  45. return $this;
  46. }
  47. /**
  48. * Returns the built node.
  49. *
  50. * @return Node The built node
  51. */
  52. public function getNode() : Node {
  53. return new Stmt\TraitUse($this->traits, $this->adaptations);
  54. }
  55. }