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