-
Notifications
You must be signed in to change notification settings - Fork 1
/
JsNodeVisitor.php
115 lines (94 loc) · 3.16 KB
/
JsNodeVisitor.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
<?php
declare(strict_types = 1);
namespace Gettext\Scanner;
use Peast\Syntax\Node\CallExpression;
use Peast\Syntax\Node\Comment;
use Peast\Syntax\Node\Node;
class JsNodeVisitor
{
protected $validFunctions;
protected $filename;
protected $functions = [];
public function __construct(string $filename, array $validFunctions = null)
{
$this->filename = $filename;
$this->validFunctions = $validFunctions;
}
public function __invoke(Node $node)
{
if ($node->getType() === 'CallExpression') {
$function = $this->createFunction($node);
if ($function) {
$this->functions[] = $function;
}
}
}
public function getFunctions(): array
{
return $this->functions;
}
protected function createFunction(CallExpression $node): ?ParsedFunction
{
$name = static::getFunctionName($node);
if (empty($name) || ($this->validFunctions !== null && !in_array($name, $this->validFunctions))) {
return null;
}
$position = $node->getLocation();
$function = new ParsedFunction(
$name,
$this->filename,
$position->getStart()->getLine(),
$position->getEnd()->getLine()
);
static::addComments($function, $node->getCallee());
foreach ($node->getArguments() as $argument) {
switch ($argument->getType()) {
case 'Literal':
$function->addArgument($argument->getValue());
static::addComments($function, $argument);
break;
case 'TemplateLiteral':
if ($argument->getExpressions()) {
$function->addArgument();
break;
}
$quasis = $argument->getQuasis();
$quasis = array_shift($quasis);
$function->addArgument($quasis->getValue());
static::addComments($function, $argument);
break;
default:
$function->addArgument();
}
}
return $function;
}
protected static function getFunctionName(CallExpression $node): ?string
{
$callee = $node->getCallee();
switch ($callee->getType()) {
case 'Identifier':
return $callee->getName();
case 'MemberExpression':
return $callee->getProperty()->getName();
default:
return null;
}
}
protected static function addComments(ParsedFunction $function, Node $node): void
{
foreach ($node->getLeadingComments() as $comment) {
$function->addComment(static::getComment($comment));
}
}
protected static function getComment(Comment $comment): string
{
$text = $comment->getText();
$lines = array_map(function ($line) {
$line = ltrim($line, "#*/ \t");
$line = rtrim($line, "#*/ \t");
return trim($line);
}, explode("\n", $text));
return trim(implode("\n", $lines));
}
}