PageRenderTime 60ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/minify/matthiasmullie-minify/src/CSS.php

https://bitbucket.org/moodle/moodle
PHP | 780 lines | 422 code | 80 blank | 278 comment | 20 complexity | c0e0009c7e6df862c9d88d82aa039d3f MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1, BSD-3-Clause, MIT, GPL-3.0
  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 static($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->extractCalcs();
  261. $css = $this->replace($css);
  262. $css = $this->stripWhitespace($css);
  263. $css = $this->shortenColors($css);
  264. $css = $this->shortenZeroes($css);
  265. $css = $this->shortenFontWeights($css);
  266. $css = $this->stripEmptyTags($css);
  267. // restore the string we've extracted earlier
  268. $css = $this->restoreExtractedData($css);
  269. $source = is_int($source) ? '' : $source;
  270. $parents = $source ? array_merge($parents, array($source)) : $parents;
  271. $css = $this->combineImports($source, $css, $parents);
  272. $css = $this->importFiles($source, $css);
  273. /*
  274. * If we'll save to a new path, we'll have to fix the relative paths
  275. * to be relative no longer to the source file, but to the new path.
  276. * If we don't write to a file, fall back to same path so no
  277. * conversion happens (because we still want it to go through most
  278. * of the move code, which also addresses url() & @import syntax...)
  279. */
  280. $converter = $this->getPathConverter($source, $path ?: $source);
  281. $css = $this->move($converter, $css);
  282. // combine css
  283. $content .= $css;
  284. }
  285. $content = $this->moveImportsToTop($content);
  286. return $content;
  287. }
  288. /**
  289. * Moving a css file should update all relative urls.
  290. * Relative references (e.g. ../images/image.gif) in a certain css file,
  291. * will have to be updated when a file is being saved at another location
  292. * (e.g. ../../images/image.gif, if the new CSS file is 1 folder deeper).
  293. *
  294. * @param ConverterInterface $converter Relative path converter
  295. * @param string $content The CSS content to update relative urls for
  296. *
  297. * @return string
  298. */
  299. protected function move(ConverterInterface $converter, $content)
  300. {
  301. /*
  302. * Relative path references will usually be enclosed by url(). @import
  303. * is an exception, where url() is not necessary around the path (but is
  304. * allowed).
  305. * This *could* be 1 regular expression, where both regular expressions
  306. * in this array are on different sides of a |. But we're using named
  307. * patterns in both regexes, the same name on both regexes. This is only
  308. * possible with a (?J) modifier, but that only works after a fairly
  309. * recent PCRE version. That's why I'm doing 2 separate regular
  310. * expressions & combining the matches after executing of both.
  311. */
  312. $relativeRegexes = array(
  313. // url(xxx)
  314. '/
  315. # open url()
  316. url\(
  317. \s*
  318. # open path enclosure
  319. (?P<quotes>["\'])?
  320. # fetch path
  321. (?P<path>.+?)
  322. # close path enclosure
  323. (?(quotes)(?P=quotes))
  324. \s*
  325. # close url()
  326. \)
  327. /ix',
  328. // @import "xxx"
  329. '/
  330. # import statement
  331. @import
  332. # whitespace
  333. \s+
  334. # we don\'t have to check for @import url(), because the
  335. # condition above will already catch these
  336. # open path enclosure
  337. (?P<quotes>["\'])
  338. # fetch path
  339. (?P<path>.+?)
  340. # close path enclosure
  341. (?P=quotes)
  342. /ix',
  343. );
  344. // find all relative urls in css
  345. $matches = array();
  346. foreach ($relativeRegexes as $relativeRegex) {
  347. if (preg_match_all($relativeRegex, $content, $regexMatches, PREG_SET_ORDER)) {
  348. $matches = array_merge($matches, $regexMatches);
  349. }
  350. }
  351. $search = array();
  352. $replace = array();
  353. // loop all urls
  354. foreach ($matches as $match) {
  355. // determine if it's a url() or an @import match
  356. $type = (strpos($match[0], '@import') === 0 ? 'import' : 'url');
  357. $url = $match['path'];
  358. if ($this->canImportByPath($url)) {
  359. // attempting to interpret GET-params makes no sense, so let's discard them for awhile
  360. $params = strrchr($url, '?');
  361. $url = $params ? substr($url, 0, -strlen($params)) : $url;
  362. // fix relative url
  363. $url = $converter->convert($url);
  364. // now that the path has been converted, re-apply GET-params
  365. $url .= $params;
  366. }
  367. /*
  368. * Urls with control characters above 0x7e should be quoted.
  369. * According to Mozilla's parser, whitespace is only allowed at the
  370. * end of unquoted urls.
  371. * Urls with `)` (as could happen with data: uris) should also be
  372. * quoted to avoid being confused for the url() closing parentheses.
  373. * And urls with a # have also been reported to cause issues.
  374. * Urls with quotes inside should also remain escaped.
  375. *
  376. * @see https://developer.mozilla.org/nl/docs/Web/CSS/url#The_url()_functional_notation
  377. * @see https://hg.mozilla.org/mozilla-central/rev/14abca4e7378
  378. * @see https://github.com/matthiasmullie/minify/issues/193
  379. */
  380. $url = trim($url);
  381. if (preg_match('/[\s\)\'"#\x{7f}-\x{9f}]/u', $url)) {
  382. $url = $match['quotes'] . $url . $match['quotes'];
  383. }
  384. // build replacement
  385. $search[] = $match[0];
  386. if ($type === 'url') {
  387. $replace[] = 'url('.$url.')';
  388. } elseif ($type === 'import') {
  389. $replace[] = '@import "'.$url.'"';
  390. }
  391. }
  392. // replace urls
  393. return str_replace($search, $replace, $content);
  394. }
  395. /**
  396. * Shorthand hex color codes.
  397. * #FF0000 -> #F00.
  398. *
  399. * @param string $content The CSS content to shorten the hex color codes for
  400. *
  401. * @return string
  402. */
  403. protected function shortenColors($content)
  404. {
  405. $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);
  406. // remove alpha channel if it's pointless...
  407. $content = preg_replace('/(?<=[: ])#([0-9a-z]{6})ff?(?=[; }])/i', '#$1', $content);
  408. $content = preg_replace('/(?<=[: ])#([0-9a-z]{3})f?(?=[; }])/i', '#$1', $content);
  409. $colors = array(
  410. // we can shorten some even more by replacing them with their color name
  411. '#F0FFFF' => 'azure',
  412. '#F5F5DC' => 'beige',
  413. '#A52A2A' => 'brown',
  414. '#FF7F50' => 'coral',
  415. '#FFD700' => 'gold',
  416. '#808080' => 'gray',
  417. '#008000' => 'green',
  418. '#4B0082' => 'indigo',
  419. '#FFFFF0' => 'ivory',
  420. '#F0E68C' => 'khaki',
  421. '#FAF0E6' => 'linen',
  422. '#800000' => 'maroon',
  423. '#000080' => 'navy',
  424. '#808000' => 'olive',
  425. '#CD853F' => 'peru',
  426. '#FFC0CB' => 'pink',
  427. '#DDA0DD' => 'plum',
  428. '#800080' => 'purple',
  429. '#F00' => 'red',
  430. '#FA8072' => 'salmon',
  431. '#A0522D' => 'sienna',
  432. '#C0C0C0' => 'silver',
  433. '#FFFAFA' => 'snow',
  434. '#D2B48C' => 'tan',
  435. '#FF6347' => 'tomato',
  436. '#EE82EE' => 'violet',
  437. '#F5DEB3' => 'wheat',
  438. // or the other way around
  439. 'WHITE' => '#fff',
  440. 'BLACK' => '#000',
  441. );
  442. return preg_replace_callback(
  443. '/(?<=[: ])('.implode('|', array_keys($colors)).')(?=[; }])/i',
  444. function ($match) use ($colors) {
  445. return $colors[strtoupper($match[0])];
  446. },
  447. $content
  448. );
  449. }
  450. /**
  451. * Shorten CSS font weights.
  452. *
  453. * @param string $content The CSS content to shorten the font weights for
  454. *
  455. * @return string
  456. */
  457. protected function shortenFontWeights($content)
  458. {
  459. $weights = array(
  460. 'normal' => 400,
  461. 'bold' => 700,
  462. );
  463. $callback = function ($match) use ($weights) {
  464. return $match[1].$weights[$match[2]];
  465. };
  466. return preg_replace_callback('/(font-weight\s*:\s*)('.implode('|', array_keys($weights)).')(?=[;}])/', $callback, $content);
  467. }
  468. /**
  469. * Shorthand 0 values to plain 0, instead of e.g. -0em.
  470. *
  471. * @param string $content The CSS content to shorten the zero values for
  472. *
  473. * @return string
  474. */
  475. protected function shortenZeroes($content)
  476. {
  477. // we don't want to strip units in `calc()` expressions:
  478. // `5px - 0px` is valid, but `5px - 0` is not
  479. // `10px * 0` is valid (equates to 0), and so is `10 * 0px`, but
  480. // `10 * 0` is invalid
  481. // we've extracted calcs earlier, so we don't need to worry about this
  482. // reusable bits of code throughout these regexes:
  483. // before & after are used to make sure we don't match lose unintended
  484. // 0-like values (e.g. in #000, or in http://url/1.0)
  485. // units can be stripped from 0 values, or used to recognize non 0
  486. // values (where wa may be able to strip a .0 suffix)
  487. $before = '(?<=[:(, ])';
  488. $after = '(?=[ ,);}])';
  489. $units = '(em|ex|%|px|cm|mm|in|pt|pc|ch|rem|vh|vw|vmin|vmax|vm)';
  490. // strip units after zeroes (0px -> 0)
  491. // NOTE: it should be safe to remove all units for a 0 value, but in
  492. // practice, Webkit (especially Safari) seems to stumble over at least
  493. // 0%, potentially other units as well. Only stripping 'px' for now.
  494. // @see https://github.com/matthiasmullie/minify/issues/60
  495. $content = preg_replace('/'.$before.'(-?0*(\.0+)?)(?<=0)px'.$after.'/', '\\1', $content);
  496. // strip 0-digits (.0 -> 0)
  497. $content = preg_replace('/'.$before.'\.0+'.$units.'?'.$after.'/', '0\\1', $content);
  498. // strip trailing 0: 50.10 -> 50.1, 50.10px -> 50.1px
  499. $content = preg_replace('/'.$before.'(-?[0-9]+\.[0-9]+)0+'.$units.'?'.$after.'/', '\\1\\2', $content);
  500. // strip trailing 0: 50.00 -> 50, 50.00px -> 50px
  501. $content = preg_replace('/'.$before.'(-?[0-9]+)\.0+'.$units.'?'.$after.'/', '\\1\\2', $content);
  502. // strip leading 0: 0.1 -> .1, 01.1 -> 1.1
  503. $content = preg_replace('/'.$before.'(-?)0+([0-9]*\.[0-9]+)'.$units.'?'.$after.'/', '\\1\\2\\3', $content);
  504. // strip negative zeroes (-0 -> 0) & truncate zeroes (00 -> 0)
  505. $content = preg_replace('/'.$before.'-?0+'.$units.'?'.$after.'/', '0\\1', $content);
  506. // IE doesn't seem to understand a unitless flex-basis value (correct -
  507. // it goes against the spec), so let's add it in again (make it `%`,
  508. // which is only 1 char: 0%, 0px, 0 anything, it's all just the same)
  509. // @see https://developer.mozilla.org/nl/docs/Web/CSS/flex
  510. $content = preg_replace('/flex:([0-9]+\s[0-9]+\s)0([;\}])/', 'flex:${1}0%${2}', $content);
  511. $content = preg_replace('/flex-basis:0([;\}])/', 'flex-basis:0%${1}', $content);
  512. return $content;
  513. }
  514. /**
  515. * Strip empty tags from source code.
  516. *
  517. * @param string $content
  518. *
  519. * @return string
  520. */
  521. protected function stripEmptyTags($content)
  522. {
  523. $content = preg_replace('/(?<=^)[^\{\};]+\{\s*\}/', '', $content);
  524. $content = preg_replace('/(?<=(\}|;))[^\{\};]+\{\s*\}/', '', $content);
  525. return $content;
  526. }
  527. /**
  528. * Strip comments from source code.
  529. */
  530. protected function stripComments()
  531. {
  532. // PHP only supports $this inside anonymous functions since 5.4
  533. $minifier = $this;
  534. $callback = function ($match) use ($minifier) {
  535. $count = count($minifier->extracted);
  536. $placeholder = '/*'.$count.'*/';
  537. $minifier->extracted[$placeholder] = $match[0];
  538. return $placeholder;
  539. };
  540. // Moodle-specific change MDL-68191 starts.
  541. /* This was the old code:
  542. $this->registerPattern('/\n?\/\*(!|.*?@license|.*?@preserve).*?\*\/\n?/s', $callback);
  543. */
  544. // This is the new, more accurate and faster regex.
  545. $this->registerPattern('/
  546. # optional newline
  547. \n?
  548. # start comment
  549. \/\*
  550. # comment content
  551. (?:
  552. # either starts with an !
  553. !
  554. |
  555. # or, after some number of characters which do not end the comment
  556. (?:(?!\*\/).)*?
  557. # there is either a @license or @preserve tag
  558. @(?:license|preserve)
  559. )
  560. # then match to the end of the comment
  561. .*?\*\/\n?
  562. /ixs', $callback);
  563. // Moodle-specific change MDL-68191.
  564. $this->registerPattern('/\/\*.*?\*\//s', '');
  565. }
  566. /**
  567. * Strip whitespace.
  568. *
  569. * @param string $content The CSS content to strip the whitespace for
  570. *
  571. * @return string
  572. */
  573. protected function stripWhitespace($content)
  574. {
  575. // remove leading & trailing whitespace
  576. $content = preg_replace('/^\s*/m', '', $content);
  577. $content = preg_replace('/\s*$/m', '', $content);
  578. // replace newlines with a single space
  579. $content = preg_replace('/\s+/', ' ', $content);
  580. // remove whitespace around meta characters
  581. // inspired by stackoverflow.com/questions/15195750/minify-compress-css-with-regex
  582. $content = preg_replace('/\s*([\*$~^|]?+=|[{};,>~]|!important\b)\s*/', '$1', $content);
  583. $content = preg_replace('/([\[(:>\+])\s+/', '$1', $content);
  584. $content = preg_replace('/\s+([\]\)>\+])/', '$1', $content);
  585. $content = preg_replace('/\s+(:)(?![^\}]*\{)/', '$1', $content);
  586. // whitespace around + and - can only be stripped inside some pseudo-
  587. // classes, like `:nth-child(3+2n)`
  588. // not in things like `calc(3px + 2px)`, shorthands like `3px -2px`, or
  589. // selectors like `div.weird- p`
  590. $pseudos = array('nth-child', 'nth-last-child', 'nth-last-of-type', 'nth-of-type');
  591. $content = preg_replace('/:('.implode('|', $pseudos).')\(\s*([+-]?)\s*(.+?)\s*([+-]?)\s*(.*?)\s*\)/', ':$1($2$3$4$5)', $content);
  592. // remove semicolon/whitespace followed by closing bracket
  593. $content = str_replace(';}', '}', $content);
  594. return trim($content);
  595. }
  596. /**
  597. * Replace all `calc()` occurrences.
  598. */
  599. protected function extractCalcs()
  600. {
  601. // PHP only supports $this inside anonymous functions since 5.4
  602. $minifier = $this;
  603. $callback = function ($match) use ($minifier) {
  604. $length = strlen($match[1]);
  605. $expr = '';
  606. $opened = 0;
  607. for ($i = 0; $i < $length; $i++) {
  608. $char = $match[1][$i];
  609. $expr .= $char;
  610. if ($char === '(') {
  611. $opened++;
  612. } elseif ($char === ')' && --$opened === 0) {
  613. break;
  614. }
  615. }
  616. $rest = str_replace($expr, '', $match[1]);
  617. $expr = trim(substr($expr, 1, -1));
  618. $count = count($minifier->extracted);
  619. $placeholder = 'calc('.$count.')';
  620. $minifier->extracted[$placeholder] = 'calc('.$expr.')';
  621. return $placeholder.$rest;
  622. };
  623. $this->registerPattern('/calc(\(.+?)(?=$|;|}|calc\()/', $callback);
  624. $this->registerPattern('/calc(\(.+?)(?=$|;|}|calc\()/m', $callback);
  625. }
  626. /**
  627. * Check if file is small enough to be imported.
  628. *
  629. * @param string $path The path to the file
  630. *
  631. * @return bool
  632. */
  633. protected function canImportBySize($path)
  634. {
  635. return ($size = @filesize($path)) && $size <= $this->maxImportSize * 1024;
  636. }
  637. /**
  638. * Check if file a file can be imported, going by the path.
  639. *
  640. * @param string $path
  641. *
  642. * @return bool
  643. */
  644. protected function canImportByPath($path)
  645. {
  646. return preg_match('/^(data:|https?:|\\/)/', $path) === 0;
  647. }
  648. /**
  649. * Return a converter to update relative paths to be relative to the new
  650. * destination.
  651. *
  652. * @param string $source
  653. * @param string $target
  654. *
  655. * @return ConverterInterface
  656. */
  657. protected function getPathConverter($source, $target)
  658. {
  659. return new Converter($source, $target);
  660. }
  661. }