]> git.immae.eu Git - github/wallabag/wallabag.git/blob - vendor/symfony/twig-bridge/Symfony/Bridge/Twig/Translation/TwigExtractor.php
twig implementation
[github/wallabag/wallabag.git] / vendor / symfony / twig-bridge / Symfony / Bridge / Twig / Translation / TwigExtractor.php
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\Bridge\Twig\Translation;
13
14 use Symfony\Component\Finder\Finder;
15 use Symfony\Component\Translation\Extractor\ExtractorInterface;
16 use Symfony\Component\Translation\MessageCatalogue;
17
18 /**
19 * TwigExtractor extracts translation messages from a twig template.
20 *
21 * @author Michel Salib <michelsalib@hotmail.com>
22 * @author Fabien Potencier <fabien@symfony.com>
23 */
24 class TwigExtractor implements ExtractorInterface
25 {
26 /**
27 * Default domain for found messages.
28 *
29 * @var string
30 */
31 private $defaultDomain = 'messages';
32
33 /**
34 * Prefix for found message.
35 *
36 * @var string
37 */
38 private $prefix = '';
39
40 /**
41 * The twig environment.
42 *
43 * @var \Twig_Environment
44 */
45 private $twig;
46
47 public function __construct(\Twig_Environment $twig)
48 {
49 $this->twig = $twig;
50 }
51
52 /**
53 * {@inheritDoc}
54 */
55 public function extract($directory, MessageCatalogue $catalogue)
56 {
57 // load any existing translation files
58 $finder = new Finder();
59 $files = $finder->files()->name('*.twig')->in($directory);
60 foreach ($files as $file) {
61 $this->extractTemplate(file_get_contents($file->getPathname()), $catalogue);
62 }
63 }
64
65 /**
66 * {@inheritDoc}
67 */
68 public function setPrefix($prefix)
69 {
70 $this->prefix = $prefix;
71 }
72
73 protected function extractTemplate($template, MessageCatalogue $catalogue)
74 {
75 $visitor = $this->twig->getExtension('translator')->getTranslationNodeVisitor();
76 $visitor->enable();
77
78 $this->twig->parse($this->twig->tokenize($template));
79
80 foreach ($visitor->getMessages() as $message) {
81 $catalogue->set(trim($message[0]), $this->prefix.trim($message[0]), $message[1] ? $message[1] : $this->defaultDomain);
82 }
83
84 $visitor->disable();
85 }
86 }