Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
MagentoImport.php
Go to the documentation of this file.
1 <?php
7 
16 
22 {
27  '#//@magento_import(?P<reference>\s+\(reference\))?\s+[\'\"](?P<path>(?![/\\\]|\w:[/\\\])[^\"\']+)[\'\"]\s*?;#';
28 
32  protected $design;
33 
37  protected $fileSource;
38 
42  protected $errorHandler;
43 
47  protected $assetRepo;
48 
53  protected $themeList;
54 
58  private $themeProvider;
59 
67  public function __construct(
71  \Magento\Framework\View\Asset\Repository $assetRepo,
72  \Magento\Framework\View\Design\Theme\ListInterface $themeList
73  ) {
74  $this->design = $design;
75  $this->fileSource = $fileSource;
76  $this->errorHandler = $errorHandler;
77  $this->assetRepo = $assetRepo;
78  $this->themeList = $themeList;
79  }
80 
84  public function process(\Magento\Framework\View\Asset\PreProcessor\Chain $chain)
85  {
86  $asset = $chain->getAsset();
87  $replaceCallback = function ($matchContent) use ($asset) {
88  return $this->replace($matchContent, $asset);
89  };
90  $chain->setContent(preg_replace_callback(self::REPLACE_PATTERN, $replaceCallback, $chain->getContent()));
91  }
92 
100  protected function replace(array $matchedContent, LocalInterface $asset)
101  {
102  $importsContent = '';
103  try {
104  $matchedFileId = $matchedContent['path'];
105  $isReference = !empty($matchedContent['reference']);
106  $relatedAsset = $this->assetRepo->createRelated($matchedFileId, $asset);
107  $resolvedPath = $relatedAsset->getFilePath();
108  $importFiles = $this->fileSource->getFiles($this->getTheme($relatedAsset), $resolvedPath);
110  foreach ($importFiles as $importFile) {
111  $referenceString = $isReference ? '(reference) ' : '';
112  $importsContent .= $importFile->getModule()
113  ? "@import $referenceString'{$importFile->getModule()}::{$resolvedPath}';\n"
114  : "@import $referenceString'{$matchedFileId}';\n";
115  }
116  } catch (\LogicException $e) {
117  $this->errorHandler->processException($e);
118  }
119  return $importsContent;
120  }
121 
128  protected function getTheme(LocalInterface $asset)
129  {
130  $context = $asset->getContext();
131  if ($context instanceof FallbackContext) {
132  return $this->getThemeProvider()->getThemeByFullPath(
133  $context->getAreaCode() . '/' . $context->getThemePath()
134  );
135  }
136  return $this->design->getDesignTheme();
137  }
138 
143  private function getThemeProvider()
144  {
145  if (null === $this->themeProvider) {
146  $this->themeProvider = ObjectManager::getInstance()->get(ThemeProviderInterface::class);
147  }
148 
149  return $this->themeProvider;
150  }
151 }
__construct(DesignInterface $design, CollectorInterface $fileSource, ErrorHandlerInterface $errorHandler, \Magento\Framework\View\Asset\Repository $assetRepo, \Magento\Framework\View\Design\Theme\ListInterface $themeList)
process(\Magento\Framework\View\Asset\PreProcessor\Chain $chain)