TranslationReader.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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\Component\Translation\Reader;
  11. use Symfony\Component\Finder\Finder;
  12. use Symfony\Component\Translation\Loader\LoaderInterface;
  13. use Symfony\Component\Translation\MessageCatalogue;
  14. /**
  15. * TranslationReader reads translation messages from translation files.
  16. *
  17. * @author Michel Salib <michelsalib@hotmail.com>
  18. */
  19. class TranslationReader implements TranslationReaderInterface
  20. {
  21. /**
  22. * Loaders used for import.
  23. *
  24. * @var array<string, LoaderInterface>
  25. */
  26. private array $loaders = [];
  27. /**
  28. * Adds a loader to the translation extractor.
  29. *
  30. * @param string $format The format of the loader
  31. */
  32. public function addLoader(string $format, LoaderInterface $loader)
  33. {
  34. $this->loaders[$format] = $loader;
  35. }
  36. public function read(string $directory, MessageCatalogue $catalogue)
  37. {
  38. if (!is_dir($directory)) {
  39. return;
  40. }
  41. foreach ($this->loaders as $format => $loader) {
  42. // load any existing translation files
  43. $finder = new Finder();
  44. $extension = $catalogue->getLocale().'.'.$format;
  45. $files = $finder->files()->name('*.'.$extension)->in($directory);
  46. foreach ($files as $file) {
  47. $domain = substr($file->getFilename(), 0, -1 * \strlen($extension) - 1);
  48. $catalogue->addCatalogue($loader->load($file->getPathname(), $catalogue->getLocale(), $domain));
  49. }
  50. }
  51. }
  52. }