1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the PHP Translation package. |
5
|
|
|
* |
6
|
|
|
* (c) PHP Translation team <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Translation\Extractor\FileExtractor; |
13
|
|
|
|
14
|
|
|
use PhpParser\Error; |
15
|
|
|
use PhpParser\NodeTraverser; |
16
|
|
|
use PhpParser\NodeVisitor; |
17
|
|
|
use PhpParser\ParserFactory; |
18
|
|
|
use Symfony\Component\Finder\SplFileInfo; |
19
|
|
|
use Translation\Extractor\Model\SourceCollection; |
20
|
|
|
use Translation\Extractor\Visitor\Visitor; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @author Tobias Nyholm <[email protected]> |
24
|
|
|
*/ |
25
|
|
|
final class PHPFileExtractor implements FileExtractor |
26
|
|
|
{ |
27
|
|
|
/** |
28
|
|
|
* @var Visitor[]|NodeVisitor[] |
29
|
|
|
*/ |
30
|
|
|
private $visitors = []; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* {@inheritdoc} |
34
|
|
|
*/ |
35
|
33 |
|
public function getSourceLocations(SplFileInfo $file, SourceCollection $collection): void |
36
|
|
|
{ |
37
|
33 |
|
$path = $file->getRelativePath(); |
38
|
33 |
|
$parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7); |
39
|
33 |
|
$traverser = new NodeTraverser(); |
40
|
33 |
|
foreach ($this->visitors as $v) { |
41
|
33 |
|
$v->init($collection, $file); |
42
|
33 |
|
$traverser->addVisitor($v); |
|
|
|
|
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
try { |
46
|
33 |
|
$tokens = $parser->parse($file->getContents()); |
47
|
33 |
|
$traverser->traverse($tokens); |
48
|
|
|
} catch (Error $e) { |
49
|
|
|
trigger_error(sprintf('Skipping file "%s" because of parse Error: %s. ', $path, $e->getMessage())); |
50
|
|
|
} |
51
|
33 |
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* {@inheritdoc} |
55
|
|
|
*/ |
56
|
1 |
|
public function supportsExtension(string $extension): bool |
57
|
|
|
{ |
58
|
1 |
|
return \in_array($extension, ['php', 'php5', 'phtml']); |
59
|
|
|
} |
60
|
|
|
|
61
|
33 |
|
public function addVisitor(NodeVisitor $visitor): void |
62
|
|
|
{ |
63
|
33 |
|
$this->visitors[] = $visitor; |
64
|
33 |
|
} |
65
|
|
|
} |
66
|
|
|
|
If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:
If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.