TwigExtractor.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bridge\Twig\Translation;
  11. use Symfony\Component\Finder\Finder;
  12. use Symfony\Component\Translation\Extractor\ExtractorInterface;
  13. use Symfony\Component\Translation\MessageCatalogue;
  14. /**
  15. * TwigExtractor extracts translation messages from a twig template.
  16. *
  17. * @author Michel Salib <michelsalib@hotmail.com>
  18. * @author Fabien Potencier <fabien@symfony.com>
  19. */
  20. class TwigExtractor implements ExtractorInterface
  21. {
  22. /**
  23. * Default domain for found messages.
  24. *
  25. * @var string
  26. */
  27. private $defaultDomain = 'messages';
  28. /**
  29. * Prefix for found message.
  30. *
  31. * @var string
  32. */
  33. private $prefix = '';
  34. /**
  35. * The twig environment.
  36. *
  37. * @var \Twig_Environment
  38. */
  39. private $twig;
  40. public function __construct(\Twig_Environment $twig)
  41. {
  42. $this->twig = $twig;
  43. }
  44. /**
  45. * {@inheritDoc}
  46. */
  47. public function extract($directory, MessageCatalogue $catalogue)
  48. {
  49. // load any existing translation files
  50. $finder = new Finder();
  51. $files = $finder->files()->name('*.twig')->in($directory);
  52. foreach ($files as $file) {
  53. $this->extractTemplate(file_get_contents($file->getPathname()), $catalogue);
  54. }
  55. }
  56. /**
  57. * {@inheritDoc}
  58. */
  59. public function setPrefix($prefix)
  60. {
  61. $this->prefix = $prefix;
  62. }
  63. protected function extractTemplate($template, MessageCatalogue $catalogue)
  64. {
  65. $visitor = $this->twig->getExtension('translator')->getTranslationNodeVisitor();
  66. $visitor->enable();
  67. $this->twig->parse($this->twig->tokenize($template));
  68. foreach ($visitor->getMessages() as $message) {
  69. $catalogue->set(trim($message[0]), $this->prefix.trim($message[0]), $message[1] ? $message[1] : $this->defaultDomain);
  70. }
  71. $visitor->disable();
  72. }
  73. }