PrintableNewAnonClassNode.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php declare(strict_types=1);
  2. namespace PhpParser\Internal;
  3. use PhpParser\Node;
  4. use PhpParser\Node\Expr;
  5. /**
  6. * This node is used internally by the format-preserving pretty printer to print anonymous classes.
  7. *
  8. * The normal anonymous class structure violates assumptions about the order of token offsets.
  9. * Namely, the constructor arguments are part of the Expr\New_ node and follow the class node, even
  10. * though they are actually interleaved with them. This special node type is used temporarily to
  11. * restore a sane token offset order.
  12. *
  13. * @internal
  14. */
  15. class PrintableNewAnonClassNode extends Expr {
  16. /** @var Node\AttributeGroup[] PHP attribute groups */
  17. public array $attrGroups;
  18. /** @var int Modifiers */
  19. public int $flags;
  20. /** @var (Node\Arg|Node\VariadicPlaceholder)[] Arguments */
  21. public array $args;
  22. /** @var null|Node\Name Name of extended class */
  23. public ?Node\Name $extends;
  24. /** @var Node\Name[] Names of implemented interfaces */
  25. public array $implements;
  26. /** @var Node\Stmt[] Statements */
  27. public array $stmts;
  28. /**
  29. * @param Node\AttributeGroup[] $attrGroups PHP attribute groups
  30. * @param (Node\Arg|Node\VariadicPlaceholder)[] $args Arguments
  31. * @param Node\Name|null $extends Name of extended class
  32. * @param Node\Name[] $implements Names of implemented interfaces
  33. * @param Node\Stmt[] $stmts Statements
  34. * @param array<string, mixed> $attributes Attributes
  35. */
  36. public function __construct(
  37. array $attrGroups, int $flags, array $args, ?Node\Name $extends, array $implements,
  38. array $stmts, array $attributes
  39. ) {
  40. parent::__construct($attributes);
  41. $this->attrGroups = $attrGroups;
  42. $this->flags = $flags;
  43. $this->args = $args;
  44. $this->extends = $extends;
  45. $this->implements = $implements;
  46. $this->stmts = $stmts;
  47. }
  48. public static function fromNewNode(Expr\New_ $newNode): self {
  49. $class = $newNode->class;
  50. assert($class instanceof Node\Stmt\Class_);
  51. // We don't assert that $class->name is null here, to allow consumers to assign unique names
  52. // to anonymous classes for their own purposes. We simplify ignore the name here.
  53. return new self(
  54. $class->attrGroups, $class->flags, $newNode->args, $class->extends, $class->implements,
  55. $class->stmts, $newNode->getAttributes()
  56. );
  57. }
  58. public function getType(): string {
  59. return 'Expr_PrintableNewAnonClass';
  60. }
  61. public function getSubNodeNames(): array {
  62. return ['attrGroups', 'flags', 'args', 'extends', 'implements', 'stmts'];
  63. }
  64. }