CSS.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. <?php
  2. namespace MatthiasMullie\Minify;
  3. use MatthiasMullie\Minify\Exceptions\FileImportException;
  4. use MatthiasMullie\PathConverter\ConverterInterface;
  5. use MatthiasMullie\PathConverter\Converter;
  6. /**
  7. * CSS minifier.
  8. *
  9. * Please report bugs on https://github.com/matthiasmullie/minify/issues
  10. *
  11. * @author Matthias Mullie <minify@mullie.eu>
  12. * @author Tijs Verkoyen <minify@verkoyen.eu>
  13. * @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
  14. * @license MIT License
  15. */
  16. class CSS extends Minify
  17. {
  18. /**
  19. * @var int
  20. */
  21. protected $maxImportSize = 5;
  22. /**
  23. * @var string[]
  24. */
  25. protected $importExtensions = array(
  26. 'gif' => 'data:image/gif',
  27. 'png' => 'data:image/png',
  28. 'jpe' => 'data:image/jpeg',
  29. 'jpg' => 'data:image/jpeg',
  30. 'jpeg' => 'data:image/jpeg',
  31. 'svg' => 'data:image/svg+xml',
  32. 'woff' => 'data:application/x-font-woff',
  33. 'tif' => 'image/tiff',
  34. 'tiff' => 'image/tiff',
  35. 'xbm' => 'image/x-xbitmap',
  36. );
  37. /**
  38. * Set the maximum size if files to be imported.
  39. *
  40. * Files larger than this size (in kB) will not be imported into the CSS.
  41. * Importing files into the CSS as data-uri will save you some connections,
  42. * but we should only import relatively small decorative images so that our
  43. * CSS file doesn't get too bulky.
  44. *
  45. * @param int $size Size in kB
  46. */
  47. public function setMaxImportSize($size)
  48. {
  49. $this->maxImportSize = $size;
  50. }
  51. /**
  52. * Set the type of extensions to be imported into the CSS (to save network
  53. * connections).
  54. * Keys of the array should be the file extensions & respective values
  55. * should be the data type.
  56. *
  57. * @param string[] $extensions Array of file extensions
  58. */
  59. public function setImportExtensions(array $extensions)
  60. {
  61. $this->importExtensions = $extensions;
  62. }
  63. /**
  64. * Move any import statements to the top.
  65. *
  66. * @param string $content Nearly finished CSS content
  67. *
  68. * @return string
  69. */
  70. protected function moveImportsToTop($content)
  71. {
  72. if (preg_match_all('/@import[^;]+;/', $content, $matches)) {
  73. // remove from content
  74. foreach ($matches[0] as $import) {
  75. $content = str_replace($import, '', $content);
  76. }
  77. // add to top
  78. $content = implode('', $matches[0]).$content;
  79. }
  80. return $content;
  81. }
  82. /**
  83. * Combine CSS from import statements.
  84. *
  85. * @import's will be loaded and their content merged into the original file,
  86. * to save HTTP requests.
  87. *
  88. * @param string $source The file to combine imports for
  89. * @param string $content The CSS content to combine imports for
  90. * @param string[] $parents Parent paths, for circular reference checks
  91. *
  92. * @return string
  93. *
  94. * @throws FileImportException
  95. */
  96. protected function combineImports($source, $content, $parents)
  97. {
  98. $importRegexes = array(
  99. // @import url(xxx)
  100. '/
  101. # import statement
  102. @import
  103. # whitespace
  104. \s+
  105. # open url()
  106. url\(
  107. # (optional) open path enclosure
  108. (?P<quotes>["\']?)
  109. # fetch path
  110. (?P<path>.+?)
  111. # (optional) close path enclosure
  112. (?P=quotes)
  113. # close url()
  114. \)
  115. # (optional) trailing whitespace
  116. \s*
  117. # (optional) media statement(s)
  118. (?P<media>[^;]*)
  119. # (optional) trailing whitespace
  120. \s*
  121. # (optional) closing semi-colon
  122. ;?
  123. /ix',
  124. // @import 'xxx'
  125. '/
  126. # import statement
  127. @import
  128. # whitespace
  129. \s+
  130. # open path enclosure
  131. (?P<quotes>["\'])
  132. # fetch path
  133. (?P<path>.+?)
  134. # close path enclosure
  135. (?P=quotes)
  136. # (optional) trailing whitespace
  137. \s*
  138. # (optional) media statement(s)
  139. (?P<media>[^;]*)
  140. # (optional) trailing whitespace
  141. \s*
  142. # (optional) closing semi-colon
  143. ;?
  144. /ix',
  145. );
  146. // find all relative imports in css
  147. $matches = array();
  148. foreach ($importRegexes as $importRegex) {
  149. if (preg_match_all($importRegex, $content, $regexMatches, PREG_SET_ORDER)) {
  150. $matches = array_merge($matches, $regexMatches);
  151. }
  152. }
  153. $search = array();
  154. $replace = array();
  155. // loop the matches
  156. foreach ($matches as $match) {
  157. // get the path for the file that will be imported
  158. $importPath = dirname($source).'/'.$match['path'];
  159. // only replace the import with the content if we can grab the
  160. // content of the file
  161. if (!$this->canImportByPath($match['path']) || !$this->canImportFile($importPath)) {
  162. continue;
  163. }
  164. // check if current file was not imported previously in the same
  165. // import chain.
  166. if (in_array($importPath, $parents)) {
  167. throw new FileImportException('Failed to import file "'.$importPath.'": circular reference detected.');
  168. }
  169. // grab referenced file & minify it (which may include importing
  170. // yet other @import statements recursively)
  171. $minifier = new static($importPath);
  172. $importContent = $minifier->execute($source, $parents);
  173. // check if this is only valid for certain media
  174. if (!empty($match['media'])) {
  175. $importContent = '@media '.$match['media'].'{'.$importContent.'}';
  176. }
  177. // add to replacement array
  178. $search[] = $match[0];
  179. $replace[] = $importContent;
  180. }
  181. // replace the import statements
  182. return str_replace($search, $replace, $content);
  183. }
  184. /**
  185. * Import files into the CSS, base64-ized.
  186. *
  187. * @url(image.jpg) images will be loaded and their content merged into the
  188. * original file, to save HTTP requests.
  189. *
  190. * @param string $source The file to import files for
  191. * @param string $content The CSS content to import files for
  192. *
  193. * @return string
  194. */
  195. protected function importFiles($source, $content)
  196. {
  197. $regex = '/url\((["\']?)(.+?)\\1\)/i';
  198. if ($this->importExtensions && preg_match_all($regex, $content, $matches, PREG_SET_ORDER)) {
  199. $search = array();
  200. $replace = array();
  201. // loop the matches
  202. foreach ($matches as $match) {
  203. $extension = substr(strrchr($match[2], '.'), 1);
  204. if ($extension && !array_key_exists($extension, $this->importExtensions)) {
  205. continue;
  206. }
  207. // get the path for the file that will be imported
  208. $path = $match[2];
  209. $path = dirname($source).'/'.$path;
  210. // only replace the import with the content if we're able to get
  211. // the content of the file, and it's relatively small
  212. if ($this->canImportFile($path) && $this->canImportBySize($path)) {
  213. // grab content && base64-ize
  214. $importContent = $this->load($path);
  215. $importContent = base64_encode($importContent);
  216. // build replacement
  217. $search[] = $match[0];
  218. $replace[] = 'url('.$this->importExtensions[$extension].';base64,'.$importContent.')';
  219. }
  220. }
  221. // replace the import statements
  222. $content = str_replace($search, $replace, $content);
  223. }
  224. return $content;
  225. }
  226. /**
  227. * Minify the data.
  228. * Perform CSS optimizations.
  229. *
  230. * @param string[optional] $path Path to write the data to
  231. * @param string[] $parents Parent paths, for circular reference checks
  232. *
  233. * @return string The minified data
  234. */
  235. public function execute($path = null, $parents = array())
  236. {
  237. $content = '';
  238. // loop CSS data (raw data and files)
  239. foreach ($this->data as $source => $css) {
  240. /*
  241. * Let's first take out strings & comments, since we can't just
  242. * remove whitespace anywhere. If whitespace occurs inside a string,
  243. * we should leave it alone. E.g.:
  244. * p { content: "a test" }
  245. */
  246. $this->extractStrings();
  247. $this->stripComments();
  248. $css = $this->replace($css);
  249. $css = $this->stripWhitespace($css);
  250. $css = $this->shortenHex($css);
  251. $css = $this->shortenZeroes($css);
  252. $css = $this->shortenFontWeights($css);
  253. $css = $this->stripEmptyTags($css);
  254. // restore the string we've extracted earlier
  255. $css = $this->restoreExtractedData($css);
  256. $source = is_int($source) ? '' : $source;
  257. $parents = $source ? array_merge($parents, array($source)) : $parents;
  258. $css = $this->combineImports($source, $css, $parents);
  259. $css = $this->importFiles($source, $css);
  260. /*
  261. * If we'll save to a new path, we'll have to fix the relative paths
  262. * to be relative no longer to the source file, but to the new path.
  263. * If we don't write to a file, fall back to same path so no
  264. * conversion happens (because we still want it to go through most
  265. * of the move code, which also addresses url() & @import syntax...)
  266. */
  267. $converter = $this->getPathConverter($source, $path ?: $source);
  268. $css = $this->move($converter, $css);
  269. // combine css
  270. $content .= $css;
  271. }
  272. $content = $this->moveImportsToTop($content);
  273. return $content;
  274. }
  275. /**
  276. * Moving a css file should update all relative urls.
  277. * Relative references (e.g. ../images/image.gif) in a certain css file,
  278. * will have to be updated when a file is being saved at another location
  279. * (e.g. ../../images/image.gif, if the new CSS file is 1 folder deeper).
  280. *
  281. * @param ConverterInterface $converter Relative path converter
  282. * @param string $content The CSS content to update relative urls for
  283. *
  284. * @return string
  285. */
  286. protected function move(ConverterInterface $converter, $content)
  287. {
  288. /*
  289. * Relative path references will usually be enclosed by url(). @import
  290. * is an exception, where url() is not necessary around the path (but is
  291. * allowed).
  292. * This *could* be 1 regular expression, where both regular expressions
  293. * in this array are on different sides of a |. But we're using named
  294. * patterns in both regexes, the same name on both regexes. This is only
  295. * possible with a (?J) modifier, but that only works after a fairly
  296. * recent PCRE version. That's why I'm doing 2 separate regular
  297. * expressions & combining the matches after executing of both.
  298. */
  299. $relativeRegexes = array(
  300. // url(xxx)
  301. '/
  302. # open url()
  303. url\(
  304. \s*
  305. # open path enclosure
  306. (?P<quotes>["\'])?
  307. # fetch path
  308. (?P<path>.+?)
  309. # close path enclosure
  310. (?(quotes)(?P=quotes))
  311. \s*
  312. # close url()
  313. \)
  314. /ix',
  315. // @import "xxx"
  316. '/
  317. # import statement
  318. @import
  319. # whitespace
  320. \s+
  321. # we don\'t have to check for @import url(), because the
  322. # condition above will already catch these
  323. # open path enclosure
  324. (?P<quotes>["\'])
  325. # fetch path
  326. (?P<path>.+?)
  327. # close path enclosure
  328. (?P=quotes)
  329. /ix',
  330. );
  331. // find all relative urls in css
  332. $matches = array();
  333. foreach ($relativeRegexes as $relativeRegex) {
  334. if (preg_match_all($relativeRegex, $content, $regexMatches, PREG_SET_ORDER)) {
  335. $matches = array_merge($matches, $regexMatches);
  336. }
  337. }
  338. $search = array();
  339. $replace = array();
  340. // loop all urls
  341. foreach ($matches as $match) {
  342. // determine if it's a url() or an @import match
  343. $type = (strpos($match[0], '@import') === 0 ? 'import' : 'url');
  344. $url = $match['path'];
  345. if ($this->canImportByPath($url)) {
  346. // attempting to interpret GET-params makes no sense, so let's discard them for awhile
  347. $params = strrchr($url, '?');
  348. $url = $params ? substr($url, 0, -strlen($params)) : $url;
  349. // fix relative url
  350. $url = $converter->convert($url);
  351. // now that the path has been converted, re-apply GET-params
  352. $url .= $params;
  353. }
  354. // build replacement
  355. $search[] = $match[0];
  356. if ($type === 'url') {
  357. $replace[] = 'url('.$url.')';
  358. } elseif ($type === 'import') {
  359. $replace[] = '@import "'.$url.'"';
  360. }
  361. }
  362. // replace urls
  363. return str_replace($search, $replace, $content);
  364. }
  365. /**
  366. * Shorthand hex color codes.
  367. * #FF0000 -> #F00.
  368. *
  369. * @param string $content The CSS content to shorten the hex color codes for
  370. *
  371. * @return string
  372. */
  373. protected function shortenHex($content)
  374. {
  375. $content = preg_replace('/(?<=[: ])#([0-9a-z])\\1([0-9a-z])\\2([0-9a-z])\\3(?=[; }])/i', '#$1$2$3', $content);
  376. // we can shorten some even more by replacing them with their color name
  377. $colors = array(
  378. '#F0FFFF' => 'azure',
  379. '#F5F5DC' => 'beige',
  380. '#A52A2A' => 'brown',
  381. '#FF7F50' => 'coral',
  382. '#FFD700' => 'gold',
  383. '#808080' => 'gray',
  384. '#008000' => 'green',
  385. '#4B0082' => 'indigo',
  386. '#FFFFF0' => 'ivory',
  387. '#F0E68C' => 'khaki',
  388. '#FAF0E6' => 'linen',
  389. '#800000' => 'maroon',
  390. '#000080' => 'navy',
  391. '#808000' => 'olive',
  392. '#CD853F' => 'peru',
  393. '#FFC0CB' => 'pink',
  394. '#DDA0DD' => 'plum',
  395. '#800080' => 'purple',
  396. '#F00' => 'red',
  397. '#FA8072' => 'salmon',
  398. '#A0522D' => 'sienna',
  399. '#C0C0C0' => 'silver',
  400. '#FFFAFA' => 'snow',
  401. '#D2B48C' => 'tan',
  402. '#FF6347' => 'tomato',
  403. '#EE82EE' => 'violet',
  404. '#F5DEB3' => 'wheat',
  405. );
  406. return preg_replace_callback(
  407. '/(?<=[: ])('.implode(array_keys($colors), '|').')(?=[; }])/i',
  408. function ($match) use ($colors) {
  409. return $colors[strtoupper($match[0])];
  410. },
  411. $content
  412. );
  413. }
  414. /**
  415. * Shorten CSS font weights.
  416. *
  417. * @param string $content The CSS content to shorten the font weights for
  418. *
  419. * @return string
  420. */
  421. protected function shortenFontWeights($content)
  422. {
  423. $weights = array(
  424. 'normal' => 400,
  425. 'bold' => 700,
  426. );
  427. $callback = function ($match) use ($weights) {
  428. return $match[1].$weights[$match[2]];
  429. };
  430. return preg_replace_callback('/(font-weight\s*:\s*)('.implode('|', array_keys($weights)).')(?=[;}])/', $callback, $content);
  431. }
  432. /**
  433. * Shorthand 0 values to plain 0, instead of e.g. -0em.
  434. *
  435. * @param string $content The CSS content to shorten the zero values for
  436. *
  437. * @return string
  438. */
  439. protected function shortenZeroes($content)
  440. {
  441. // reusable bits of code throughout these regexes:
  442. // before & after are used to make sure we don't match lose unintended
  443. // 0-like values (e.g. in #000, or in http://url/1.0)
  444. // units can be stripped from 0 values, or used to recognize non 0
  445. // values (where wa may be able to strip a .0 suffix)
  446. $before = '(?<=[:(, ])';
  447. $after = '(?=[ ,);}])';
  448. $units = '(em|ex|%|px|cm|mm|in|pt|pc|ch|rem|vh|vw|vmin|vmax|vm)';
  449. // strip units after zeroes (0px -> 0)
  450. // NOTE: it should be safe to remove all units for a 0 value, but in
  451. // practice, Webkit (especially Safari) seems to stumble over at least
  452. // 0%, potentially other units as well. Only stripping 'px' for now.
  453. // @see https://github.com/matthiasmullie/minify/issues/60
  454. $content = preg_replace('/'.$before.'(-?0*(\.0+)?)(?<=0)px'.$after.'/', '\\1', $content);
  455. // strip 0-digits (.0 -> 0)
  456. $content = preg_replace('/'.$before.'\.0+'.$units.'?'.$after.'/', '0\\1', $content);
  457. // strip trailing 0: 50.10 -> 50.1, 50.10px -> 50.1px
  458. $content = preg_replace('/'.$before.'(-?[0-9]+\.[0-9]+)0+'.$units.'?'.$after.'/', '\\1\\2', $content);
  459. // strip trailing 0: 50.00 -> 50, 50.00px -> 50px
  460. $content = preg_replace('/'.$before.'(-?[0-9]+)\.0+'.$units.'?'.$after.'/', '\\1\\2', $content);
  461. // strip leading 0: 0.1 -> .1, 01.1 -> 1.1
  462. $content = preg_replace('/'.$before.'(-?)0+([0-9]*\.[0-9]+)'.$units.'?'.$after.'/', '\\1\\2\\3', $content);
  463. // strip negative zeroes (-0 -> 0) & truncate zeroes (00 -> 0)
  464. $content = preg_replace('/'.$before.'-?0+'.$units.'?'.$after.'/', '0\\1', $content);
  465. // remove zeroes where they make no sense in calc: e.g. calc(100px - 0)
  466. // the 0 doesn't have any effect, and this isn't even valid without unit
  467. // strip all `+ 0` or `- 0` occurrences: calc(10% + 0) -> calc(10%)
  468. // looped because there may be multiple 0s inside 1 group of parentheses
  469. do {
  470. $previous = $content;
  471. $content = preg_replace('/\(([^\(\)]+) [\+\-] 0( [^\(\)]+)?\)/', '(\\1\\2)', $content);
  472. } while ($content !== $previous);
  473. // strip all `0 +` occurrences: calc(0 + 10%) -> calc(10%)
  474. $content = preg_replace('/\(0 \+ ([^\(\)]+)\)/', '(\\1)', $content);
  475. // strip all `0 -` occurrences: calc(0 - 10%) -> calc(-10%)
  476. $content = preg_replace('/\(0 \- ([^\(\)]+)\)/', '(-\\1)', $content);
  477. // I'm not going to attempt to optimize away `x * 0` instances:
  478. // it's dumb enough code already that it likely won't occur, and it's
  479. // too complex to do right (order of operations would have to be
  480. // respected etc)
  481. // what I cared about most here was fixing incorrectly truncated units
  482. // IE doesn't seem to understand a unitless flex-basis value, so let's
  483. // add it in again (make it `%`, which is only 1 char: 0%, 0px, 0
  484. // anything, it's all just the same)
  485. $content = preg_replace('/flex:([^ ]+ [^ ]+ )0([;\}])/', 'flex:${1}0%${2}', $content);
  486. $content = preg_replace('/flex-basis:0([;\}])/', 'flex-basis:0%${1}', $content);
  487. return $content;
  488. }
  489. /**
  490. * Strip comments from source code.
  491. *
  492. * @param string $content
  493. *
  494. * @return string
  495. */
  496. protected function stripEmptyTags($content)
  497. {
  498. return preg_replace('/(^|\}|;)[^\{\};]+\{\s*\}/', '\\1', $content);
  499. }
  500. /**
  501. * Strip comments from source code.
  502. */
  503. protected function stripComments()
  504. {
  505. $this->registerPattern('/\/\*.*?\*\//s', '');
  506. }
  507. /**
  508. * Strip whitespace.
  509. *
  510. * @param string $content The CSS content to strip the whitespace for
  511. *
  512. * @return string
  513. */
  514. protected function stripWhitespace($content)
  515. {
  516. // remove leading & trailing whitespace
  517. $content = preg_replace('/^\s*/m', '', $content);
  518. $content = preg_replace('/\s*$/m', '', $content);
  519. // replace newlines with a single space
  520. $content = preg_replace('/\s+/', ' ', $content);
  521. // remove whitespace around meta characters
  522. // inspired by stackoverflow.com/questions/15195750/minify-compress-css-with-regex
  523. $content = preg_replace('/\s*([\*$~^|]?+=|[{};,>~]|!important\b)\s*/', '$1', $content);
  524. $content = preg_replace('/([\[(:])\s+/', '$1', $content);
  525. $content = preg_replace('/\s+([\]\)])/', '$1', $content);
  526. $content = preg_replace('/\s+(:)(?![^\}]*\{)/', '$1', $content);
  527. // whitespace around + and - can only be stripped in selectors, like
  528. // :nth-child(3+2n), not in things like calc(3px + 2px) or shorthands
  529. // like 3px -2px
  530. $content = preg_replace('/\s*([+-])\s*(?=[^}]*{)/', '$1', $content);
  531. // remove semicolon/whitespace followed by closing bracket
  532. $content = str_replace(';}', '}', $content);
  533. return trim($content);
  534. }
  535. /**
  536. * Check if file is small enough to be imported.
  537. *
  538. * @param string $path The path to the file
  539. *
  540. * @return bool
  541. */
  542. protected function canImportBySize($path)
  543. {
  544. return ($size = @filesize($path)) && $size <= $this->maxImportSize * 1024;
  545. }
  546. /**
  547. * Check if file a file can be imported, going by the path.
  548. *
  549. * @param string $path
  550. *
  551. * @return bool
  552. */
  553. protected function canImportByPath($path)
  554. {
  555. return preg_match('/^(data:|https?:|\\/)/', $path) === 0;
  556. }
  557. /**
  558. * Return a converter to update relative paths to be relative to the new
  559. * destination.
  560. *
  561. * @param string $source
  562. * @param string $target
  563. *
  564. * @return ConverterInterface
  565. */
  566. protected function getPathConverter($source, $target)
  567. {
  568. return new Converter($source, $target);
  569. }
  570. }