CSS.php 27 KB

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