PrintableNewAnonClassNode.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. {
  17. /** @var Node\AttributeGroup[] PHP attribute groups */
  18. public $attrGroups;
  19. /** @var Node\Arg[] Arguments */
  20. public $args;
  21. /** @var null|Node\Name Name of extended class */
  22. public $extends;
  23. /** @var Node\Name[] Names of implemented interfaces */
  24. public $implements;
  25. /** @var Node\Stmt[] Statements */
  26. public $stmts;
  27. public function __construct(
  28. array $attrGroups, array $args, Node\Name $extends = null, array $implements,
  29. array $stmts, array $attributes
  30. ) {
  31. parent::__construct($attributes);
  32. $this->attrGroups = $attrGroups;
  33. $this->args = $args;
  34. $this->extends = $extends;
  35. $this->implements = $implements;
  36. $this->stmts = $stmts;
  37. }
  38. public static function fromNewNode(Expr\New_ $newNode) {
  39. $class = $newNode->class;
  40. assert($class instanceof Node\Stmt\Class_);
  41. // We don't assert that $class->name is null here, to allow consumers to assign unique names
  42. // to anonymous classes for their own purposes. We simplify ignore the name here.
  43. return new self(
  44. $class->attrGroups, $newNode->args, $class->extends, $class->implements,
  45. $class->stmts, $newNode->getAttributes()
  46. );
  47. }
  48. public function getType() : string {
  49. return 'Expr_PrintableNewAnonClass';
  50. }
  51. public function getSubNodeNames() : array {
  52. return ['attrGroups', 'args', 'extends', 'implements', 'stmts'];
  53. }
  54. }