CSS.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  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. $importContent = $minifier->execute($source, $parents);
  183. // check if this is only valid for certain media
  184. if (!empty($match['media'])) {
  185. $importContent = '@media '.$match['media'].'{'.$importContent.'}';
  186. }
  187. // add to replacement array
  188. $search[] = $match[0];
  189. $replace[] = $importContent;
  190. }
  191. // replace the import statements
  192. return str_replace($search, $replace, $content);
  193. }
  194. /**
  195. * Import files into the CSS, base64-ized.
  196. *
  197. * @url(image.jpg) images will be loaded and their content merged into the
  198. * original file, to save HTTP requests.
  199. *
  200. * @param string $source The file to import files for
  201. * @param string $content The CSS content to import files for
  202. *
  203. * @return string
  204. */
  205. protected function importFiles($source, $content)
  206. {
  207. $regex = '/url\((["\']?)(.+?)\\1\)/i';
  208. if ($this->importExtensions && preg_match_all($regex, $content, $matches, PREG_SET_ORDER)) {
  209. $search = array();
  210. $replace = array();
  211. // loop the matches
  212. foreach ($matches as $match) {
  213. $extension = substr(strrchr($match[2], '.'), 1);
  214. if ($extension && !array_key_exists($extension, $this->importExtensions)) {
  215. continue;
  216. }
  217. // get the path for the file that will be imported
  218. $path = $match[2];
  219. $path = dirname($source).'/'.$path;
  220. // only replace the import with the content if we're able to get
  221. // the content of the file, and it's relatively small
  222. if ($this->canImportFile($path) && $this->canImportBySize($path)) {
  223. // grab content && base64-ize
  224. $importContent = $this->load($path);
  225. $importContent = base64_encode($importContent);
  226. // build replacement
  227. $search[] = $match[0];
  228. $replace[] = 'url('.$this->importExtensions[$extension].';base64,'.$importContent.')';
  229. }
  230. }
  231. // replace the import statements
  232. $content = str_replace($search, $replace, $content);
  233. }
  234. return $content;
  235. }
  236. /**
  237. * Minify the data.
  238. * Perform CSS optimizations.
  239. *
  240. * @param string[optional] $path Path to write the data to
  241. * @param string[] $parents Parent paths, for circular reference checks
  242. *
  243. * @return string The minified data
  244. */
  245. public function execute($path = null, $parents = array())
  246. {
  247. $content = '';
  248. // loop CSS data (raw data and files)
  249. foreach ($this->data as $source => $css) {
  250. /*
  251. * Let's first take out strings & comments, since we can't just
  252. * remove whitespace anywhere. If whitespace occurs inside a string,
  253. * we should leave it alone. E.g.:
  254. * p { content: "a test" }
  255. */
  256. $this->extractStrings();
  257. $this->stripComments();
  258. $css = $this->replace($css);
  259. $css = $this->stripWhitespace($css);
  260. $css = $this->shortenHex($css);
  261. $css = $this->shortenZeroes($css);
  262. $css = $this->shortenFontWeights($css);
  263. $css = $this->stripEmptyTags($css);
  264. // restore the string we've extracted earlier
  265. $css = $this->restoreExtractedData($css);
  266. $source = is_int($source) ? '' : $source;
  267. $parents = $source ? array_merge($parents, array($source)) : $parents;
  268. $css = $this->combineImports($source, $css, $parents);
  269. $css = $this->importFiles($source, $css);
  270. /*
  271. * If we'll save to a new path, we'll have to fix the relative paths
  272. * to be relative no longer to the source file, but to the new path.
  273. * If we don't write to a file, fall back to same path so no
  274. * conversion happens (because we still want it to go through most
  275. * of the move code, which also addresses url() & @import syntax...)
  276. */
  277. $converter = $this->getPathConverter($source, $path ?: $source);
  278. $css = $this->move($converter, $css);
  279. // combine css
  280. $content .= $css;
  281. }
  282. $content = $this->moveImportsToTop($content);
  283. return $content;
  284. }
  285. /**
  286. * Moving a css file should update all relative urls.
  287. * Relative references (e.g. ../images/image.gif) in a certain css file,
  288. * will have to be updated when a file is being saved at another location
  289. * (e.g. ../../images/image.gif, if the new CSS file is 1 folder deeper).
  290. *
  291. * @param ConverterInterface $converter Relative path converter
  292. * @param string $content The CSS content to update relative urls for
  293. *
  294. * @return string
  295. */
  296. protected function move(ConverterInterface $converter, $content)
  297. {
  298. /*
  299. * Relative path references will usually be enclosed by url(). @import
  300. * is an exception, where url() is not necessary around the path (but is
  301. * allowed).
  302. * This *could* be 1 regular expression, where both regular expressions
  303. * in this array are on different sides of a |. But we're using named
  304. * patterns in both regexes, the same name on both regexes. This is only
  305. * possible with a (?J) modifier, but that only works after a fairly
  306. * recent PCRE version. That's why I'm doing 2 separate regular
  307. * expressions & combining the matches after executing of both.
  308. */
  309. $relativeRegexes = array(
  310. // url(xxx)
  311. '/
  312. # open url()
  313. url\(
  314. \s*
  315. # open path enclosure
  316. (?P<quotes>["\'])?
  317. # fetch path
  318. (?P<path>.+?)
  319. # close path enclosure
  320. (?(quotes)(?P=quotes))
  321. \s*
  322. # close url()
  323. \)
  324. /ix',
  325. // @import "xxx"
  326. '/
  327. # import statement
  328. @import
  329. # whitespace
  330. \s+
  331. # we don\'t have to check for @import url(), because the
  332. # condition above will already catch these
  333. # open path enclosure
  334. (?P<quotes>["\'])
  335. # fetch path
  336. (?P<path>.+?)
  337. # close path enclosure
  338. (?P=quotes)
  339. /ix',
  340. );
  341. // find all relative urls in css
  342. $matches = array();
  343. foreach ($relativeRegexes as $relativeRegex) {
  344. if (preg_match_all($relativeRegex, $content, $regexMatches, PREG_SET_ORDER)) {
  345. $matches = array_merge($matches, $regexMatches);
  346. }
  347. }
  348. $search = array();
  349. $replace = array();
  350. // loop all urls
  351. foreach ($matches as $match) {
  352. // determine if it's a url() or an @import match
  353. $type = (strpos($match[0], '@import') === 0 ? 'import' : 'url');
  354. $url = $match['path'];
  355. if ($this->canImportByPath($url)) {
  356. // attempting to interpret GET-params makes no sense, so let's discard them for awhile
  357. $params = strrchr($url, '?');
  358. $url = $params ? substr($url, 0, -strlen($params)) : $url;
  359. // fix relative url
  360. $url = $converter->convert($url);
  361. // now that the path has been converted, re-apply GET-params
  362. $url .= $params;
  363. }
  364. /*
  365. * Urls with control characters above 0x7e should be quoted.
  366. * According to Mozilla's parser, whitespace is only allowed at the
  367. * end of unquoted urls.
  368. * Urls with `)` (as could happen with data: uris) should also be
  369. * quoted to avoid being confused for the url() closing parentheses.
  370. * And urls with a # have also been reported to cause issues.
  371. * Urls with quotes inside should also remain escaped.
  372. *
  373. * @see https://developer.mozilla.org/nl/docs/Web/CSS/url#The_url()_functional_notation
  374. * @see https://hg.mozilla.org/mozilla-central/rev/14abca4e7378
  375. * @see https://github.com/matthiasmullie/minify/issues/193
  376. */
  377. $url = trim($url);
  378. if (preg_match('/[\s\)\'"#\x{7f}-\x{9f}]/u', $url)) {
  379. $url = $match['quotes'] . $url . $match['quotes'];
  380. }
  381. // build replacement
  382. $search[] = $match[0];
  383. if ($type === 'url') {
  384. $replace[] = 'url('.$url.')';
  385. } elseif ($type === 'import') {
  386. $replace[] = '@import "'.$url.'"';
  387. }
  388. }
  389. // replace urls
  390. return str_replace($search, $replace, $content);
  391. }
  392. /**
  393. * Shorthand hex color codes.
  394. * #FF0000 -> #F00.
  395. *
  396. * @param string $content The CSS content to shorten the hex color codes for
  397. *
  398. * @return string
  399. */
  400. protected function shortenHex($content)
  401. {
  402. $content = preg_replace('/(?<=[: ])#([0-9a-z])\\1([0-9a-z])\\2([0-9a-z])\\3(?=[; }])/i', '#$1$2$3', $content);
  403. // we can shorten some even more by replacing them with their color name
  404. $colors = array(
  405. '#F0FFFF' => 'azure',
  406. '#F5F5DC' => 'beige',
  407. '#A52A2A' => 'brown',
  408. '#FF7F50' => 'coral',
  409. '#FFD700' => 'gold',
  410. '#808080' => 'gray',
  411. '#008000' => 'green',
  412. '#4B0082' => 'indigo',
  413. '#FFFFF0' => 'ivory',
  414. '#F0E68C' => 'khaki',
  415. '#FAF0E6' => 'linen',
  416. '#800000' => 'maroon',
  417. '#000080' => 'navy',
  418. '#808000' => 'olive',
  419. '#CD853F' => 'peru',
  420. '#FFC0CB' => 'pink',
  421. '#DDA0DD' => 'plum',
  422. '#800080' => 'purple',
  423. '#F00' => 'red',
  424. '#FA8072' => 'salmon',
  425. '#A0522D' => 'sienna',
  426. '#C0C0C0' => 'silver',
  427. '#FFFAFA' => 'snow',
  428. '#D2B48C' => 'tan',
  429. '#FF6347' => 'tomato',
  430. '#EE82EE' => 'violet',
  431. '#F5DEB3' => 'wheat',
  432. );
  433. return preg_replace_callback(
  434. '/(?<=[: ])('.implode(array_keys($colors), '|').')(?=[; }])/i',
  435. function ($match) use ($colors) {
  436. return $colors[strtoupper($match[0])];
  437. },
  438. $content
  439. );
  440. }
  441. /**
  442. * Shorten CSS font weights.
  443. *
  444. * @param string $content The CSS content to shorten the font weights for
  445. *
  446. * @return string
  447. */
  448. protected function shortenFontWeights($content)
  449. {
  450. $weights = array(
  451. 'normal' => 400,
  452. 'bold' => 700,
  453. );
  454. $callback = function ($match) use ($weights) {
  455. return $match[1].$weights[$match[2]];
  456. };
  457. return preg_replace_callback('/(font-weight\s*:\s*)('.implode('|', array_keys($weights)).')(?=[;}])/', $callback, $content);
  458. }
  459. /**
  460. * Shorthand 0 values to plain 0, instead of e.g. -0em.
  461. *
  462. * @param string $content The CSS content to shorten the zero values for
  463. *
  464. * @return string
  465. */
  466. protected function shortenZeroes($content)
  467. {
  468. // we don't want to strip units in `calc()` expressions:
  469. // `5px - 0px` is valid, but `5px - 0` is not
  470. // `10px * 0` is valid (equates to 0), and so is `10 * 0px`, but
  471. // `10 * 0` is invalid
  472. // best to just leave `calc()`s alone, even if they could be optimized
  473. // (which is a whole other undertaking, where units & order of
  474. // operations all need to be considered...)
  475. $calcs = $this->findCalcs($content);
  476. $content = str_replace($calcs, array_keys($calcs), $content);
  477. // reusable bits of code throughout these regexes:
  478. // before & after are used to make sure we don't match lose unintended
  479. // 0-like values (e.g. in #000, or in http://url/1.0)
  480. // units can be stripped from 0 values, or used to recognize non 0
  481. // values (where wa may be able to strip a .0 suffix)
  482. $before = '(?<=[:(, ])';
  483. $after = '(?=[ ,);}])';
  484. $units = '(em|ex|%|px|cm|mm|in|pt|pc|ch|rem|vh|vw|vmin|vmax|vm)';
  485. // strip units after zeroes (0px -> 0)
  486. // NOTE: it should be safe to remove all units for a 0 value, but in
  487. // practice, Webkit (especially Safari) seems to stumble over at least
  488. // 0%, potentially other units as well. Only stripping 'px' for now.
  489. // @see https://github.com/matthiasmullie/minify/issues/60
  490. $content = preg_replace('/'.$before.'(-?0*(\.0+)?)(?<=0)px'.$after.'/', '\\1', $content);
  491. // strip 0-digits (.0 -> 0)
  492. $content = preg_replace('/'.$before.'\.0+'.$units.'?'.$after.'/', '0\\1', $content);
  493. // strip trailing 0: 50.10 -> 50.1, 50.10px -> 50.1px
  494. $content = preg_replace('/'.$before.'(-?[0-9]+\.[0-9]+)0+'.$units.'?'.$after.'/', '\\1\\2', $content);
  495. // strip trailing 0: 50.00 -> 50, 50.00px -> 50px
  496. $content = preg_replace('/'.$before.'(-?[0-9]+)\.0+'.$units.'?'.$after.'/', '\\1\\2', $content);
  497. // strip leading 0: 0.1 -> .1, 01.1 -> 1.1
  498. $content = preg_replace('/'.$before.'(-?)0+([0-9]*\.[0-9]+)'.$units.'?'.$after.'/', '\\1\\2\\3', $content);
  499. // strip negative zeroes (-0 -> 0) & truncate zeroes (00 -> 0)
  500. $content = preg_replace('/'.$before.'-?0+'.$units.'?'.$after.'/', '0\\1', $content);
  501. // IE doesn't seem to understand a unitless flex-basis value (correct -
  502. // it goes against the spec), so let's add it in again (make it `%`,
  503. // which is only 1 char: 0%, 0px, 0 anything, it's all just the same)
  504. // @see https://developer.mozilla.org/nl/docs/Web/CSS/flex
  505. $content = preg_replace('/flex:([0-9]+\s[0-9]+\s)0([;\}])/', 'flex:${1}0%${2}', $content);
  506. $content = preg_replace('/flex-basis:0([;\}])/', 'flex-basis:0%${1}', $content);
  507. // restore `calc()` expressions
  508. $content = str_replace(array_keys($calcs), $calcs, $content);
  509. return $content;
  510. }
  511. /**
  512. * Strip empty tags from source code.
  513. *
  514. * @param string $content
  515. *
  516. * @return string
  517. */
  518. protected function stripEmptyTags($content)
  519. {
  520. $content = preg_replace('/(?<=^)[^\{\};]+\{\s*\}/', '', $content);
  521. $content = preg_replace('/(?<=(\}|;))[^\{\};]+\{\s*\}/', '', $content);
  522. return $content;
  523. }
  524. /**
  525. * Strip comments from source code.
  526. */
  527. protected function stripComments()
  528. {
  529. $this->registerPattern('/\/\*.*?\*\//s', '');
  530. }
  531. /**
  532. * Strip whitespace.
  533. *
  534. * @param string $content The CSS content to strip the whitespace for
  535. *
  536. * @return string
  537. */
  538. protected function stripWhitespace($content)
  539. {
  540. // remove leading & trailing whitespace
  541. $content = preg_replace('/^\s*/m', '', $content);
  542. $content = preg_replace('/\s*$/m', '', $content);
  543. // replace newlines with a single space
  544. $content = preg_replace('/\s+/', ' ', $content);
  545. // remove whitespace around meta characters
  546. // inspired by stackoverflow.com/questions/15195750/minify-compress-css-with-regex
  547. $content = preg_replace('/\s*([\*$~^|]?+=|[{};,>~]|!important\b)\s*/', '$1', $content);
  548. $content = preg_replace('/([\[(:])\s+/', '$1', $content);
  549. $content = preg_replace('/\s+([\]\)])/', '$1', $content);
  550. $content = preg_replace('/\s+(:)(?![^\}]*\{)/', '$1', $content);
  551. // whitespace around + and - can only be stripped inside some pseudo-
  552. // classes, like `:nth-child(3+2n)`
  553. // not in things like `calc(3px + 2px)`, shorthands like `3px -2px`, or
  554. // selectors like `div.weird- p`
  555. $pseudos = array('nth-child', 'nth-last-child', 'nth-last-of-type', 'nth-of-type');
  556. $content = preg_replace('/:('.implode('|', $pseudos).')\(\s*([+-]?)\s*(.+?)\s*([+-]?)\s*(.*?)\s*\)/', ':$1($2$3$4$5)', $content);
  557. // remove semicolon/whitespace followed by closing bracket
  558. $content = str_replace(';}', '}', $content);
  559. return trim($content);
  560. }
  561. /**
  562. * Find all `calc()` occurrences.
  563. *
  564. * @param string $content The CSS content to find `calc()`s in.
  565. *
  566. * @return string[]
  567. */
  568. protected function findCalcs($content)
  569. {
  570. $results = array();
  571. preg_match_all('/calc(\(.+?)(?=$|;|calc\()/', $content, $matches, PREG_SET_ORDER);
  572. foreach ($matches as $match) {
  573. $length = strlen($match[1]);
  574. $expr = '';
  575. $opened = 0;
  576. for ($i = 0; $i < $length; $i++) {
  577. $char = $match[1][$i];
  578. $expr .= $char;
  579. if ($char === '(') {
  580. $opened++;
  581. } elseif ($char === ')' && --$opened === 0) {
  582. break;
  583. }
  584. }
  585. $results['calc('.count($results).')'] = 'calc'.$expr;
  586. }
  587. return $results;
  588. }
  589. /**
  590. * Check if file is small enough to be imported.
  591. *
  592. * @param string $path The path to the file
  593. *
  594. * @return bool
  595. */
  596. protected function canImportBySize($path)
  597. {
  598. return ($size = @filesize($path)) && $size <= $this->maxImportSize * 1024;
  599. }
  600. /**
  601. * Check if file a file can be imported, going by the path.
  602. *
  603. * @param string $path
  604. *
  605. * @return bool
  606. */
  607. protected function canImportByPath($path)
  608. {
  609. return preg_match('/^(data:|https?:|\\/)/', $path) === 0;
  610. }
  611. /**
  612. * Return a converter to update relative paths to be relative to the new
  613. * destination.
  614. *
  615. * @param string $source
  616. * @param string $target
  617. *
  618. * @return ConverterInterface
  619. */
  620. protected function getPathConverter($source, $target)
  621. {
  622. return new Converter($source, $target);
  623. }
  624. }