Skip to content

Commit

Permalink
added finder
Browse files Browse the repository at this point in the history
  • Loading branch information
schmittjoh committed Apr 6, 2012
1 parent b0ea3e5 commit 84fc68c
Showing 1 changed file with 85 additions and 0 deletions.
85 changes: 85 additions & 0 deletions lib/PHPParser/Finder.php
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;
}
}

0 comments on commit 84fc68c

Please sign in to comment.