TranslationTrait.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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\Command;
  11. use Symfony\Component\Translation\MessageCatalogue;
  12. use Symfony\Component\Translation\MessageCatalogueInterface;
  13. use Symfony\Component\Translation\TranslatorBag;
  14. /**
  15. * @internal
  16. */
  17. trait TranslationTrait
  18. {
  19. private function readLocalTranslations(array $locales, array $domains, array $transPaths): TranslatorBag
  20. {
  21. $bag = new TranslatorBag();
  22. foreach ($locales as $locale) {
  23. $catalogue = new MessageCatalogue($locale);
  24. foreach ($transPaths as $path) {
  25. $this->reader->read($path, $catalogue);
  26. }
  27. if ($domains) {
  28. foreach ($domains as $domain) {
  29. $bag->addCatalogue($this->filterCatalogue($catalogue, $domain));
  30. }
  31. } else {
  32. $bag->addCatalogue($catalogue);
  33. }
  34. }
  35. return $bag;
  36. }
  37. private function filterCatalogue(MessageCatalogue $catalogue, string $domain): MessageCatalogue
  38. {
  39. $filteredCatalogue = new MessageCatalogue($catalogue->getLocale());
  40. // extract intl-icu messages only
  41. $intlDomain = $domain.MessageCatalogueInterface::INTL_DOMAIN_SUFFIX;
  42. if ($intlMessages = $catalogue->all($intlDomain)) {
  43. $filteredCatalogue->add($intlMessages, $intlDomain);
  44. }
  45. // extract all messages and subtract intl-icu messages
  46. if ($messages = array_diff($catalogue->all($domain), $intlMessages)) {
  47. $filteredCatalogue->add($messages, $domain);
  48. }
  49. foreach ($catalogue->getResources() as $resource) {
  50. $filteredCatalogue->addResource($resource);
  51. }
  52. if ($metadata = $catalogue->getMetadata('', $intlDomain)) {
  53. foreach ($metadata as $k => $v) {
  54. $filteredCatalogue->setMetadata($k, $v, $intlDomain);
  55. }
  56. }
  57. if ($metadata = $catalogue->getMetadata('', $domain)) {
  58. foreach ($metadata as $k => $v) {
  59. $filteredCatalogue->setMetadata($k, $v, $domain);
  60. }
  61. }
  62. return $filteredCatalogue;
  63. }
  64. }