CSS.php 20 KB

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