TraitUse.php 1.6 KB

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