CallLike.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php declare(strict_types=1);
  2. namespace PhpParser\Node\Expr;
  3. use PhpParser\Node\Arg;
  4. use PhpParser\Node\Expr;
  5. use PhpParser\Node\VariadicPlaceholder;
  6. abstract class CallLike extends Expr {
  7. /**
  8. * Return raw arguments, which may be actual Args, or VariadicPlaceholders for first-class
  9. * callables.
  10. *
  11. * @return array<Arg|VariadicPlaceholder>
  12. */
  13. abstract public function getRawArgs(): array;
  14. /**
  15. * Returns whether this call expression is actually a first class callable.
  16. */
  17. public function isFirstClassCallable(): bool {
  18. $rawArgs = $this->getRawArgs();
  19. return count($rawArgs) === 1 && current($rawArgs) instanceof VariadicPlaceholder;
  20. }
  21. /**
  22. * Assert that this is not a first-class callable and return only ordinary Args.
  23. *
  24. * @return Arg[]
  25. */
  26. public function getArgs(): array {
  27. assert(!$this->isFirstClassCallable());
  28. return $this->getRawArgs();
  29. }
  30. /**
  31. * Retrieves a specific argument from the raw arguments.
  32. *
  33. * Returns the named argument that matches the given `$name`, or the
  34. * positional (unnamed) argument that exists at the given `$position`,
  35. * otherwise, returns `null` for first-class callables or if no match is found.
  36. */
  37. public function getArg(string $name, int $position): ?Arg {
  38. if ($this->isFirstClassCallable()) {
  39. return null;
  40. }
  41. foreach ($this->getRawArgs() as $i => $arg) {
  42. if ($arg->unpack) {
  43. continue;
  44. }
  45. if (
  46. ($arg->name !== null && $arg->name->toString() === $name)
  47. || ($arg->name === null && $i === $position)
  48. ) {
  49. return $arg;
  50. }
  51. }
  52. return null;
  53. }
  54. }