| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
namespace Symfony\Component\Translation\Extractor; |
| 13 |
|
| 14 |
use PhpParser\NodeTraverser; |
| 15 |
use PhpParser\NodeVisitor; |
| 16 |
use PhpParser\Parser; |
| 17 |
use PhpParser\ParserFactory; |
| 18 |
use Symfony\Component\Finder\Finder; |
| 19 |
use Symfony\Component\Translation\Extractor\Visitor\AbstractVisitor; |
| 20 |
use Symfony\Component\Translation\MessageCatalogue; |
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
final class PhpAstExtractor extends AbstractFileExtractor implements ExtractorInterface |
| 28 |
{ |
| 29 |
private Parser $parser; |
| 30 |
|
| 31 |
public function __construct( |
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
private readonly iterable $visitors, |
| 36 |
private string $prefix = '', |
| 37 |
) { |
| 38 |
if (!class_exists(ParserFactory::class)) { |
| 39 |
throw new \LogicException(\sprintf('You cannot use "%s" as the "nikic/php-parser" package is not installed. Try running "composer require nikic/php-parser".', static::class)); |
| 40 |
} |
| 41 |
|
| 42 |
$this->parser = (new ParserFactory())->createForHostVersion(); |
| 43 |
} |
| 44 |
|
| 45 |
public function extract(iterable|string $resource, MessageCatalogue $catalogue): void |
| 46 |
{ |
| 47 |
foreach ($this->extractFiles($resource) as $file) { |
| 48 |
$traverser = new NodeTraverser(); |
| 49 |
|
| 50 |
|
| 51 |
$nameResolver = new NodeVisitor\NameResolver(); |
| 52 |
$traverser->addVisitor($nameResolver); |
| 53 |
|
| 54 |
foreach ($this->visitors as $visitor) { |
| 55 |
$visitor->initialize($catalogue, $file, $this->prefix); |
| 56 |
$traverser->addVisitor($visitor); |
| 57 |
} |
| 58 |
|
| 59 |
$nodes = $this->parser->parse(file_get_contents($file)); |
| 60 |
$traverser->traverse($nodes); |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
public function setPrefix(string $prefix): void |
| 65 |
{ |
| 66 |
$this->prefix = $prefix; |
| 67 |
} |
| 68 |
|
| 69 |
protected function canBeExtracted(string $file): bool |
| 70 |
{ |
| 71 |
return 'php' === pathinfo($file, \PATHINFO_EXTENSION) |
| 72 |
&& $this->isFile($file) |
| 73 |
&& preg_match('/\bt\(|->trans\(|TranslatableMessage|Symfony\\\\Component\\\\Validator\\\\Constraints/i', file_get_contents($file)); |
| 74 |
} |
| 75 |
|
| 76 |
protected function extractFromDirectory(array|string $resource): iterable|Finder |
| 77 |
{ |
| 78 |
if (!class_exists(Finder::class)) { |
| 79 |
throw new \LogicException(\sprintf('You cannot use "%s" as the "symfony/finder" package is not installed. Try running "composer require symfony/finder".', static::class)); |
| 80 |
} |
| 81 |
|
| 82 |
return (new Finder())->files()->name('*.php')->in($resource); |
| 83 |
} |
| 84 |
} |