Skip to content

Commit

Permalink
Allow to extend the phpNodeVisitor #5
Browse files Browse the repository at this point in the history
  • Loading branch information
oscarotero committed Nov 18, 2019
1 parent 151ad71 commit 583fd8e
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
8 changes: 7 additions & 1 deletion src/PhpFunctionsScanner.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
namespace Gettext\Scanner;

use PhpParser\NodeTraverser;
use PhpParser\NodeVisitor;
use PhpParser\Parser;
use PhpParser\ParserFactory;

Expand All @@ -27,10 +28,15 @@ public function scan(string $code, string $filename): array
}

$traverser = new NodeTraverser();
$visitor = new PhpNodeVisitor($filename, $this->validFunctions);
$visitor = $this->createNodeVisitor($filename);
$traverser->addVisitor($visitor);
$traverser->traverse($ast);

return $visitor->getFunctions();
}

protected function createNodeVisitor(string $filename): NodeVisitor
{
return new PhpNodeVisitor($filename, $this->validFunctions);
}
}
15 changes: 14 additions & 1 deletion src/PhpNodeVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ class PhpNodeVisitor implements NodeVisitor
protected $validFunctions;
protected $filename;
protected $functions = [];
protected $argumentsHandlers = [];

public function __construct(string $filename, array $validFunctions = null)
{
Expand Down Expand Up @@ -76,7 +77,14 @@ protected function createFunction(FuncCall $node): ParsedFunction
$function->addComment(static::getComment($comment));
}

switch ($value->getType()) {
$type = $value->getType();

if (isset($this->argumentsHandlers[$type])) {
call_user_func($this->argumentsHandlers[$type], $function, $value);
continue;
}

switch ($type) {
case 'Scalar_String':
case 'Scalar_LNumber':
case 'Scalar_DNumber':
Expand All @@ -90,6 +98,11 @@ protected function createFunction(FuncCall $node): ParsedFunction
return $function;
}

public function setArgumentsHandler(string $type, callable $handler)
{
$this->argumentsHandlers[$type] = $handler;
}

protected static function getComment(Comment $comment): string
{
$text = $comment->getReformattedText();
Expand Down
2 changes: 2 additions & 0 deletions tests/assets/code.php
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,5 @@ public function test()
$test();
}
}

t("Translatable string","",["context"=>"Context string"]);

0 comments on commit 583fd8e

Please sign in to comment.