Sin descripción

QtFileLoader.php 2.5KB

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\MessageCatalogue;
  16. /**
  17. * QtFileLoader loads translations from QT Translations XML files.
  18. *
  19. * @author Benjamin Eberlei <kontakt@beberlei.de>
  20. */
  21. class QtFileLoader implements LoaderInterface
  22. {
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function load($resource, $locale, $domain = 'messages')
  27. {
  28. if (!stream_is_local($resource)) {
  29. throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource));
  30. }
  31. if (!file_exists($resource)) {
  32. throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
  33. }
  34. try {
  35. $dom = XmlUtils::loadFile($resource);
  36. } catch (\InvalidArgumentException $e) {
  37. throw new InvalidResourceException(sprintf('Unable to load "%s".', $resource), $e->getCode(), $e);
  38. }
  39. $internalErrors = libxml_use_internal_errors(true);
  40. libxml_clear_errors();
  41. $xpath = new \DOMXPath($dom);
  42. $nodes = $xpath->evaluate('//TS/context/name[text()="'.$domain.'"]');
  43. $catalogue = new MessageCatalogue($locale);
  44. if (1 == $nodes->length) {
  45. $translations = $nodes->item(0)->nextSibling->parentNode->parentNode->getElementsByTagName('message');
  46. foreach ($translations as $translation) {
  47. $translationValue = (string) $translation->getElementsByTagName('translation')->item(0)->nodeValue;
  48. if (!empty($translationValue)) {
  49. $catalogue->set(
  50. (string) $translation->getElementsByTagName('source')->item(0)->nodeValue,
  51. $translationValue,
  52. $domain
  53. );
  54. }
  55. $translation = $translation->nextSibling;
  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. }