forked from nikic/PHP-Parser
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
b0ea3e5
commit 84fc68c
Showing
1 changed file
with
85 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
<?php | ||
|
||
/** | ||
* Searches through the AST to find a node with the given specifications. | ||
* | ||
* @author Johannes M. Schmitt <schmittjoh@gmail.com> | ||
*/ | ||
class PHPParser_Finder | ||
{ | ||
private $ast; | ||
|
||
public static function create(array $ast) { | ||
return new self($ast); | ||
} | ||
|
||
public function __construct(array $ast) { | ||
$this->ast = $ast; | ||
} | ||
|
||
public function find($expr, PHPParser_Node $relativeNode = null) { | ||
$visitor = $this->createVisitor($expr); | ||
|
||
$traverser = new PHPParser_NodeTraverser(); | ||
$traverser->addVisitor($visitor); | ||
$traverser->traverse(null === $relativeNode ? $this->ast : array($relativeNode)); | ||
|
||
return $visitor->getMatches(); | ||
} | ||
|
||
private function createVisitor($expr) { | ||
$attr = $this->parseExpr($expr); | ||
|
||
return new PHPParser_NodeVisitor_Matcher($attr['class'], $attr); | ||
} | ||
|
||
private function parseExpr($expr) { | ||
$class = 'PHPParser_Node_'; | ||
|
||
$block = 'class'; | ||
$attributes = array(); | ||
for ($i=0,$c=strlen($expr); $i<$c; $i++) { | ||
switch ($char = $expr[$i]) { | ||
case '[': | ||
$block = 'attribute_key'; | ||
$attributeKey = ''; | ||
break; | ||
|
||
case '=': | ||
$block = 'attribute_value'; | ||
$attributeValue = ''; | ||
break; | ||
|
||
case ']': | ||
if (!isset($attributeKey, $attributeValue)) { | ||
throw new \InvalidArgumentException(sprintf('Unexpected "]" at position %d, no attribute key or value exists.', $i)); | ||
} | ||
$attributes[$attributeKey] = $attributeValue; | ||
unset($attributeKey, $attributeValue); | ||
break; | ||
|
||
default: | ||
switch ($block) { | ||
case 'class': | ||
$class .= $char; | ||
break; | ||
|
||
case 'attribute_key': | ||
$attributeKey .= $char; | ||
break; | ||
|
||
case 'attribute_value': | ||
$attributeValue .= $char; | ||
break; | ||
|
||
default: | ||
throw new \InvalidArgumentException(sprintf('Expected block starting element like "[", but got "%s" at position %d.', $char, $i)); | ||
} | ||
} | ||
} | ||
|
||
$attributes['class'] = $class; | ||
|
||
return $attributes; | ||
} | ||
} |