Skip to content

Instantly share code, notes, and snippets.

@kanian
Created March 19, 2019 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kanian/6d37b36c8e9e2fe24c13a1c0b22435cc to your computer and use it in GitHub Desktop.
Save kanian/6d37b36c8e9e2fe24c13a1c0b22435cc to your computer and use it in GitHub Desktop.
A PHP Parser node visitor
<?php
namespace Assoa\Parser;
use PhpParser\Node;
use PhpParser\Node\Stmt\Class_;
use Assoa\Commands\BuilderCommand;
use PhpParser\NodeVisitorAbstract;
use Assoa\Parser\INodeVisitorFactory;
use PhpParser\Node\Stmt\ClassMethod;
class ProxyNodeVisitorFactory implements INodeVisitorFactory
{
public static function get(...$args)
{
$className = $args[0];
$commands = $args[1];
$visitor = new class($className, $commands) extends NodeVisitorAbstract
{
protected $parsingTargetClass = false;
protected $isFinalClass = false;
public function __construct($className, $commands)
{
$this->commands = $commands;
$this->className = $className;
}
public function enterNode(Node $node)
{
if (($node instanceof ClassMethod) && $node->isPublic() && $this->parsingTargetClass === true) {on
if ($node->isFinal()) {
throw new InvalidArgumentException("A final class cannot be proxied");
}
if($node->name == "__construct"){
$this->commands['constructor']->execute($node);
} else {
$this->commands['method']->execute($node);
}
} elseif (($node instanceof Class_) && ($node->name == $this->className)) {
$this->parsingTargetClass = true;
}
}
public function leaveNode(Node $node)
{
if ($node instanceof Class_) {
// If the node is a class node
if ($node->name == $this->className) {
$this->commands['class']->execute();
$this->parsingTargetClass = false;
}
}
}
};
return $visitor;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment