CssOptimizer.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. <?php
  2. namespace Drupal\Core\Asset;
  3. use Drupal\Component\Utility\Unicode;
  4. /**
  5. * Optimizes a CSS asset.
  6. */
  7. class CssOptimizer implements AssetOptimizerInterface {
  8. /**
  9. * The base path used by rewriteFileURI().
  10. *
  11. * @var string
  12. */
  13. public $rewriteFileURIBasePath;
  14. /**
  15. * {@inheritdoc}
  16. */
  17. public function optimize(array $css_asset) {
  18. if ($css_asset['type'] != 'file') {
  19. throw new \Exception('Only file CSS assets can be optimized.');
  20. }
  21. if (!$css_asset['preprocess']) {
  22. throw new \Exception('Only file CSS assets with preprocessing enabled can be optimized.');
  23. }
  24. return $this->processFile($css_asset);
  25. }
  26. /**
  27. * Processes the contents of a CSS asset for cleanup.
  28. *
  29. * @param string $contents
  30. * The contents of the CSS asset.
  31. *
  32. * @return string
  33. * Contents of the CSS asset.
  34. */
  35. public function clean($contents) {
  36. // Remove multiple charset declarations for standards compliance (and fixing
  37. // Safari problems).
  38. $contents = preg_replace('/^@charset\s+[\'"](\S*?)\b[\'"];/i', '', $contents);
  39. return $contents;
  40. }
  41. /**
  42. * Build aggregate CSS file.
  43. */
  44. protected function processFile($css_asset) {
  45. $contents = $this->loadFile($css_asset['data'], TRUE);
  46. $contents = $this->clean($contents);
  47. // Get the parent directory of this file, relative to the Drupal root.
  48. $css_base_path = substr($css_asset['data'], 0, strrpos($css_asset['data'], '/'));
  49. // Store base path.
  50. $this->rewriteFileURIBasePath = $css_base_path . '/';
  51. // Anchor all paths in the CSS with its base URL, ignoring external and absolute paths.
  52. return preg_replace_callback('/url\(\s*[\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\s*\)/i', [$this, 'rewriteFileURI'], $contents);
  53. }
  54. /**
  55. * Loads the stylesheet and resolves all @import commands.
  56. *
  57. * Loads a stylesheet and replaces @import commands with the contents of the
  58. * imported file. Use this instead of file_get_contents when processing
  59. * stylesheets.
  60. *
  61. * The returned contents are compressed removing white space and comments only
  62. * when CSS aggregation is enabled. This optimization will not apply for
  63. * color.module enabled themes with CSS aggregation turned off.
  64. *
  65. * Note: the only reason this method is public is so color.module can call it;
  66. * it is not on the AssetOptimizerInterface, so future refactorings can make
  67. * it protected.
  68. *
  69. * @param $file
  70. * Name of the stylesheet to be processed.
  71. * @param $optimize
  72. * Defines if CSS contents should be compressed or not.
  73. * @param $reset_basepath
  74. * Used internally to facilitate recursive resolution of @import commands.
  75. *
  76. * @return
  77. * Contents of the stylesheet, including any resolved @import commands.
  78. */
  79. public function loadFile($file, $optimize = NULL, $reset_basepath = TRUE) {
  80. // These statics are not cache variables, so we don't use drupal_static().
  81. static $_optimize, $basepath;
  82. if ($reset_basepath) {
  83. $basepath = '';
  84. }
  85. // Store the value of $optimize for preg_replace_callback with nested
  86. // @import loops.
  87. if (isset($optimize)) {
  88. $_optimize = $optimize;
  89. }
  90. // Stylesheets are relative one to each other. Start by adding a base path
  91. // prefix provided by the parent stylesheet (if necessary).
  92. if ($basepath && !file_uri_scheme($file)) {
  93. $file = $basepath . '/' . $file;
  94. }
  95. // Store the parent base path to restore it later.
  96. $parent_base_path = $basepath;
  97. // Set the current base path to process possible child imports.
  98. $basepath = dirname($file);
  99. // Load the CSS stylesheet. We suppress errors because themes may specify
  100. // stylesheets in their .info.yml file that don't exist in the theme's path,
  101. // but are merely there to disable certain module CSS files.
  102. $content = '';
  103. if ($contents = @file_get_contents($file)) {
  104. // If a BOM is found, convert the file to UTF-8, then use substr() to
  105. // remove the BOM from the result.
  106. if ($encoding = (Unicode::encodingFromBOM($contents))) {
  107. $contents = Unicode::substr(Unicode::convertToUtf8($contents, $encoding), 1);
  108. }
  109. // If no BOM, check for fallback encoding. Per CSS spec the regex is very strict.
  110. elseif (preg_match('/^@charset "([^"]+)";/', $contents, $matches)) {
  111. if ($matches[1] !== 'utf-8' && $matches[1] !== 'UTF-8') {
  112. $contents = substr($contents, strlen($matches[0]));
  113. $contents = Unicode::convertToUtf8($contents, $matches[1]);
  114. }
  115. }
  116. // Return the processed stylesheet.
  117. $content = $this->processCss($contents, $_optimize);
  118. }
  119. // Restore the parent base path as the file and its children are processed.
  120. $basepath = $parent_base_path;
  121. return $content;
  122. }
  123. /**
  124. * Loads stylesheets recursively and returns contents with corrected paths.
  125. *
  126. * This function is used for recursive loading of stylesheets and
  127. * returns the stylesheet content with all url() paths corrected.
  128. *
  129. * @param array $matches
  130. * An array of matches by a preg_replace_callback() call that scans for
  131. * @import-ed CSS files, except for external CSS files.
  132. *
  133. * @return
  134. * The contents of the CSS file at $matches[1], with corrected paths.
  135. *
  136. * @see \Drupal\Core\Asset\AssetOptimizerInterface::loadFile()
  137. */
  138. protected function loadNestedFile($matches) {
  139. $filename = $matches[1];
  140. // Load the imported stylesheet and replace @import commands in there as
  141. // well.
  142. $file = $this->loadFile($filename, NULL, FALSE);
  143. // Determine the file's directory.
  144. $directory = dirname($filename);
  145. // If the file is in the current directory, make sure '.' doesn't appear in
  146. // the url() path.
  147. $directory = $directory == '.' ? '' : $directory . '/';
  148. // Alter all internal url() paths. Leave external paths alone. We don't need
  149. // to normalize absolute paths here because that will be done later.
  150. return preg_replace('/url\(\s*([\'"]?)(?![a-z]+:|\/+)([^\'")]+)([\'"]?)\s*\)/i', 'url(\1' . $directory . '\2\3)', $file);
  151. }
  152. /**
  153. * Processes the contents of a stylesheet for aggregation.
  154. *
  155. * @param $contents
  156. * The contents of the stylesheet.
  157. * @param $optimize
  158. * (optional) Boolean whether CSS contents should be minified. Defaults to
  159. * FALSE.
  160. *
  161. * @return
  162. * Contents of the stylesheet including the imported stylesheets.
  163. */
  164. protected function processCss($contents, $optimize = FALSE) {
  165. // Remove unwanted CSS code that cause issues.
  166. $contents = $this->clean($contents);
  167. if ($optimize) {
  168. // Perform some safe CSS optimizations.
  169. // Regexp to match comment blocks.
  170. $comment = '/\*[^*]*\*+(?:[^/*][^*]*\*+)*/';
  171. // Regexp to match double quoted strings.
  172. $double_quot = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"';
  173. // Regexp to match single quoted strings.
  174. $single_quot = "'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'";
  175. // Strip all comment blocks, but keep double/single quoted strings.
  176. $contents = preg_replace(
  177. "<($double_quot|$single_quot)|$comment>Ss",
  178. "$1",
  179. $contents
  180. );
  181. // Remove certain whitespace.
  182. // There are different conditions for removing leading and trailing
  183. // whitespace.
  184. // @see http://php.net/manual/regexp.reference.subpatterns.php
  185. $contents = preg_replace('<
  186. # Do not strip any space from within single or double quotes
  187. (' . $double_quot . '|' . $single_quot . ')
  188. # Strip leading and trailing whitespace.
  189. | \s*([@{};,])\s*
  190. # Strip only leading whitespace from:
  191. # - Closing parenthesis: Retain "@media (bar) and foo".
  192. | \s+([\)])
  193. # Strip only trailing whitespace from:
  194. # - Opening parenthesis: Retain "@media (bar) and foo".
  195. # - Colon: Retain :pseudo-selectors.
  196. | ([\(:])\s+
  197. >xSs',
  198. // Only one of the four capturing groups will match, so its reference
  199. // will contain the wanted value and the references for the
  200. // two non-matching groups will be replaced with empty strings.
  201. '$1$2$3$4',
  202. $contents
  203. );
  204. // End the file with a new line.
  205. $contents = trim($contents);
  206. $contents .= "\n";
  207. }
  208. // Replaces @import commands with the actual stylesheet content.
  209. // This happens recursively but omits external files.
  210. $contents = preg_replace_callback('/@import\s*(?:url\(\s*)?[\'"]?(?![a-z]+:)(?!\/\/)([^\'"\()]+)[\'"]?\s*\)?\s*;/', [$this, 'loadNestedFile'], $contents);
  211. return $contents;
  212. }
  213. /**
  214. * Prefixes all paths within a CSS file for processFile().
  215. *
  216. * Note: the only reason this method is public is so color.module can call it;
  217. * it is not on the AssetOptimizerInterface, so future refactorings can make
  218. * it protected.
  219. *
  220. * @param array $matches
  221. * An array of matches by a preg_replace_callback() call that scans for
  222. * url() references in CSS files, except for external or absolute ones.
  223. *
  224. * @return string
  225. * The file path.
  226. */
  227. public function rewriteFileURI($matches) {
  228. // Prefix with base and remove '../' segments where possible.
  229. $path = $this->rewriteFileURIBasePath . $matches[1];
  230. $last = '';
  231. while ($path != $last) {
  232. $last = $path;
  233. $path = preg_replace('`(^|/)(?!\.\./)([^/]+)/\.\./`', '$1', $path);
  234. }
  235. return 'url(' . file_url_transform_relative(file_create_url($path)) . ')';
  236. }
  237. }