Skip to content

Commit

Permalink
Update ClosureExporter.php
Browse files Browse the repository at this point in the history
  • Loading branch information
Shelamkoff authored Jan 11, 2023
1 parent f8cde5f commit b27d3da
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/ClosureExporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,13 +90,28 @@ protected function getVisitor(?Node\Stmt\Namespace_ $namespace, ?array $uses)
{
return new class($namespace, $uses) extends NodeVisitorAbstract
{
/**
* @var Node[]
*/
private $stack = [];
public function __construct(
private ?Node\Stmt\Namespace_ $namespace,
private ?array $uses) {
}

public function beforeTraverse(array $nodes)
{
$this->stack = [];
}

public function enterNode(Node $node)
{
if (!empty($this->stack)) {
$node->setAttribute('parent', $this->stack[count($this->stack) - 1]);
}

$this->stack[] = $node;

if ($node instanceof Name && !$node instanceof Name\FullyQualified) {
foreach ($this->uses as $use) {
$parts = [];
Expand All @@ -111,6 +126,34 @@ public function enterNode(Node $node)
}
}
}

if ($node->getAttribute('parent') instanceof Node\Expr\ConstFetch) {
if (in_array(strtolower($node->parts[0]), ['null', 'false', 'true'])) {
return $node;
}
foreach (get_defined_constants() as $name => $v) {
if ($node->parts[0] == $name) {
return new Name\FullyQualified($node->parts[0], $node->getAttributes());
}
}
}

if ($node->getAttribute('parent') instanceof Node\Expr\FuncCall) {
$code = strtolower($node->toCodeString());
$definedFunctions = get_defined_functions();
foreach ($definedFunctions['internal'] as $name) {
if ($code == $name) {
return new Name\FullyQualified($name, $node->getAttributes());
}
}

foreach ($definedFunctions['user'] as $name) {
if ($code == $name) {
return new Name\FullyQualified($name, $node->getAttributes());
}
}
}

if ($this->namespace) {
return new Name\FullyQualified(
[...$this->namespace->name->parts, ...$node->parts],
Expand All @@ -122,6 +165,10 @@ public function enterNode(Node $node)
return $node;
}

public function leaveNode(Node $node)
{
array_pop($this->stack);
}
};
}
}

0 comments on commit b27d3da

Please sign in to comment.