Created
March 19, 2019 18:44
-
-
Save kanian/6d37b36c8e9e2fe24c13a1c0b22435cc to your computer and use it in GitHub Desktop.
A PHP Parser node visitor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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