PreProcessor.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Translation\Model\Js;
  7. use Magento\Framework\App\AreaList;
  8. use Magento\Framework\TranslateInterface;
  9. use Magento\Framework\View\Asset\File\FallbackContext;
  10. use Magento\Framework\View\Asset\PreProcessor\Chain;
  11. use Magento\Framework\View\Asset\PreProcessorInterface;
  12. /**
  13. * PreProcessor responsible for replacing translation calls in js files to translated strings
  14. */
  15. class PreProcessor implements PreProcessorInterface
  16. {
  17. /**
  18. * Javascript translation configuration
  19. *
  20. * @var Config
  21. */
  22. protected $config;
  23. /**
  24. * @var AreaList
  25. */
  26. protected $areaList;
  27. /**
  28. * @var TranslateInterface
  29. */
  30. protected $translate;
  31. /**
  32. * @param Config $config
  33. * @param AreaList $areaList
  34. * @param TranslateInterface $translate
  35. */
  36. public function __construct(Config $config, AreaList $areaList, TranslateInterface $translate)
  37. {
  38. $this->config = $config;
  39. $this->areaList = $areaList;
  40. $this->translate = $translate;
  41. }
  42. /**
  43. * Transform content and/or content type for the specified preprocessing chain object
  44. *
  45. * @param Chain $chain
  46. * @return void
  47. */
  48. public function process(Chain $chain)
  49. {
  50. if ($this->config->isEmbeddedStrategy()) {
  51. $context = $chain->getAsset()->getContext();
  52. $areaCode = \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE;
  53. if ($context instanceof FallbackContext) {
  54. $areaCode = $context->getAreaCode();
  55. $this->translate->setLocale($context->getLocale());
  56. }
  57. $area = $this->areaList->getArea($areaCode);
  58. $area->load(\Magento\Framework\App\Area::PART_TRANSLATE);
  59. $chain->setContent($this->translate($chain->getContent()));
  60. }
  61. }
  62. /**
  63. * Replace translation calls with translation result and return content
  64. *
  65. * @param string $content
  66. * @return string
  67. */
  68. public function translate($content)
  69. {
  70. foreach ($this->config->getPatterns() as $pattern) {
  71. $content = preg_replace_callback($pattern, [$this, 'replaceCallback'], $content);
  72. }
  73. return $content;
  74. }
  75. /**
  76. * Replace callback for preg_replace_callback function
  77. *
  78. * @param array $matches
  79. * @return string
  80. */
  81. protected function replaceCallback($matches)
  82. {
  83. return '"' . __($matches[1]) . '"';
  84. }
  85. }