QtFileLoader.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. public function load(mixed $resource, string $locale, string $domain = 'messages'): MessageCatalogue
  25. {
  26. if (!class_exists(XmlUtils::class)) {
  27. throw new RuntimeException('Loading translations from the QT format requires the Symfony Config component.');
  28. }
  29. if (!stream_is_local($resource)) {
  30. throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource));
  31. }
  32. if (!file_exists($resource)) {
  33. throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
  34. }
  35. try {
  36. $dom = XmlUtils::loadFile($resource);
  37. } catch (\InvalidArgumentException $e) {
  38. throw new InvalidResourceException(sprintf('Unable to load "%s".', $resource), $e->getCode(), $e);
  39. }
  40. $internalErrors = libxml_use_internal_errors(true);
  41. libxml_clear_errors();
  42. $xpath = new \DOMXPath($dom);
  43. $nodes = $xpath->evaluate('//TS/context/name[text()="'.$domain.'"]');
  44. $catalogue = new MessageCatalogue($locale);
  45. if (1 == $nodes->length) {
  46. $translations = $nodes->item(0)->nextSibling->parentNode->parentNode->getElementsByTagName('message');
  47. foreach ($translations as $translation) {
  48. $translationValue = (string) $translation->getElementsByTagName('translation')->item(0)->nodeValue;
  49. if (!empty($translationValue)) {
  50. $catalogue->set(
  51. (string) $translation->getElementsByTagName('source')->item(0)->nodeValue,
  52. $translationValue,
  53. $domain
  54. );
  55. }
  56. }
  57. if (class_exists(FileResource::class)) {
  58. $catalogue->addResource(new FileResource($resource));
  59. }
  60. }
  61. libxml_use_internal_errors($internalErrors);
  62. return $catalogue;
  63. }
  64. }