Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
CssResolver.php
Go to the documentation of this file.
1 <?php
7 
9 
17 {
22  '#url\s*\(\s*(?(?=\'|").)(?!http\://|https\://|/|data\:)(.+?)(?:[\#\?].*?|[\'"])?\s*\)#';
23 
32  public function relocateRelativeUrls($cssContent, $relatedPath, $filePath)
33  {
34  $offset = FileSystem::offsetPath($relatedPath, $filePath);
35  $callback = function ($path) use ($offset) {
36  return FileSystem::normalizePath($offset . '/' . $path);
37  };
38  return $this->replaceRelativeUrls($cssContent, $callback);
39  }
40 
51  public function replaceRelativeUrls($cssContent, $inlineCallback)
52  {
53  $patterns = self::extractRelativeUrls($cssContent);
54  if ($patterns) {
55  $replace = [];
56  foreach ($patterns as $pattern => $path) {
57  if (!isset($replace[$pattern])) {
58  $newPath = call_user_func($inlineCallback, $path);
59  $newPattern = str_replace($path, $newPath, $pattern);
60  $replace[$pattern] = $newPattern;
61  }
62  }
63  if ($replace) {
64  $cssContent = str_replace(array_keys($replace), array_values($replace), $cssContent);
65  }
66  }
67  return $cssContent;
68  }
69 
76  public function aggregateImportDirectives($cssContent)
77  {
78  $parts = preg_split('/(@import\s.+?;\s*)/', $cssContent, -1, PREG_SPLIT_DELIM_CAPTURE);
79  $imports = [];
80  $css = [];
81  foreach ($parts as $part) {
82  if (0 === strpos($part, '@import', 0)) {
83  $imports[] = trim($part);
84  } else {
85  $css[] = $part;
86  }
87  }
88 
89  $result = implode($css);
90  if ($imports) {
91  $result = implode("\n", $imports)
92  . "\n/* The above import directives are aggregated from content. */\n"
93  . $result;
94  }
95  return $result;
96  }
97 
104  private static function extractRelativeUrls($cssContent)
105  {
106  preg_match_all(self::REGEX_CSS_RELATIVE_URLS, $cssContent, $matches);
107  if (!empty($matches[0]) && !empty($matches[1])) {
108  return array_combine($matches[0], $matches[1]);
109  }
110  return [];
111  }
112 }
replaceRelativeUrls($cssContent, $inlineCallback)
Definition: CssResolver.php:51
$pattern
Definition: website.php:22
relocateRelativeUrls($cssContent, $relatedPath, $filePath)
Definition: CssResolver.php:32
static offsetPath($relatedPath, $path)
Definition: FileSystem.php:209