You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.8 KiB

3 years ago
  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\Loader;
  11. use Symfony\Component\Config\Resource\FileResource;
  12. use Symfony\Component\Config\Util\XmlUtils;
  13. use Symfony\Component\Translation\Exception\InvalidResourceException;
  14. use Symfony\Component\Translation\Exception\NotFoundResourceException;
  15. use Symfony\Component\Translation\Exception\RuntimeException;
  16. use Symfony\Component\Translation\MessageCatalogue;
  17. /**
  18. * QtFileLoader loads translations from QT Translations XML files.
  19. *
  20. * @author Benjamin Eberlei <kontakt@beberlei.de>
  21. */
  22. class QtFileLoader implements LoaderInterface
  23. {
  24. /**
  25. * {@inheritdoc}
  26. */
  27. public function load($resource, string $locale, string $domain = 'messages')
  28. {
  29. if (!class_exists(XmlUtils::class)) {
  30. throw new RuntimeException('Loading translations from the QT format requires the Symfony Config component.');
  31. }
  32. if (!stream_is_local($resource)) {
  33. throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource));
  34. }
  35. if (!file_exists($resource)) {
  36. throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
  37. }
  38. try {
  39. $dom = XmlUtils::loadFile($resource);
  40. } catch (\InvalidArgumentException $e) {
  41. throw new InvalidResourceException(sprintf('Unable to load "%s".', $resource), $e->getCode(), $e);
  42. }
  43. $internalErrors = libxml_use_internal_errors(true);
  44. libxml_clear_errors();
  45. $xpath = new \DOMXPath($dom);
  46. $nodes = $xpath->evaluate('//TS/context/name[text()="'.$domain.'"]');
  47. $catalogue = new MessageCatalogue($locale);
  48. if (1 == $nodes->length) {
  49. $translations = $nodes->item(0)->nextSibling->parentNode->parentNode->getElementsByTagName('message');
  50. foreach ($translations as $translation) {
  51. $translationValue = (string) $translation->getElementsByTagName('translation')->item(0)->nodeValue;
  52. if (!empty($translationValue)) {
  53. $catalogue->set(
  54. (string) $translation->getElementsByTagName('source')->item(0)->nodeValue,
  55. $translationValue,
  56. $domain
  57. );
  58. }
  59. $translation = $translation->nextSibling;
  60. }
  61. if (class_exists(FileResource::class)) {
  62. $catalogue->addResource(new FileResource($resource));
  63. }
  64. }
  65. libxml_use_internal_errors($internalErrors);
  66. return $catalogue;
  67. }
  68. }