Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
/*
4
 * This file is part of the Symfony package.
5
 *
6
 * (c) Fabien Potencier <fabien@symfony.com>
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 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
 * PhpAstExtractor extracts translation messages from a PHP AST.
24
 *
25
 * @author Mathieu Santostefano <msantostefano@protonmail.com>
26
 */
27
final class PhpAstExtractor extends AbstractFileExtractor implements ExtractorInterface
28
{
29
    private Parser $parser;
30
 
31
    public function __construct(
32
        /**
33
         * @param iterable<AbstractVisitor&NodeVisitor> $visitors
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())->create(ParserFactory::PREFER_PHP7);
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
            /** @var AbstractVisitor&NodeVisitor $visitor */
50
            foreach ($this->visitors as $visitor) {
51
                $visitor->initialize($catalogue, $file, $this->prefix);
52
                $traverser->addVisitor($visitor);
53
            }
54
 
55
            $nodes = $this->parser->parse(file_get_contents($file));
56
            $traverser->traverse($nodes);
57
        }
58
    }
59
 
60
    public function setPrefix(string $prefix): void
61
    {
62
        $this->prefix = $prefix;
63
    }
64
 
65
    protected function canBeExtracted(string $file): bool
66
    {
67
        return 'php' === pathinfo($file, \PATHINFO_EXTENSION) && $this->isFile($file);
68
    }
69
 
70
    protected function extractFromDirectory(array|string $resource): iterable|Finder
71
    {
72
        if (!class_exists(Finder::class)) {
73
            throw new \LogicException(sprintf('You cannot use "%s" as the "symfony/finder" package is not installed. Try running "composer require symfony/finder".', static::class));
74
        }
75
 
76
        return (new Finder())->files()->name('*.php')->in($resource);
77
    }
78
}