CSSmin.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /**
  3. * Class Minify_CSSmin
  4. * @package Minify
  5. */
  6. /**
  7. * Wrapper for CSSmin
  8. *
  9. * This class uses CSSmin and Minify_CSS_UriRewriter to minify CSS and rewrite relative URIs.
  10. *
  11. * @package Minify
  12. * @author Stephen Clay <steve@mrclay.org>
  13. */
  14. class Minify_CSSmin {
  15. /**
  16. * Minify a CSS string
  17. *
  18. * @param string $css
  19. *
  20. * @param array $options available options:
  21. *
  22. * 'removeCharsets': (default true) remove all @charset at-rules
  23. *
  24. * 'prependRelativePath': (default null) if given, this string will be
  25. * prepended to all relative URIs in import/url declarations
  26. *
  27. * 'currentDir': (default null) if given, this is assumed to be the
  28. * directory of the current CSS file. Using this, minify will rewrite
  29. * all relative URIs in import/url declarations to correctly point to
  30. * the desired files. For this to work, the files *must* exist and be
  31. * visible by the PHP process.
  32. *
  33. * 'symlinks': (default = array()) If the CSS file is stored in
  34. * a symlink-ed directory, provide an array of link paths to
  35. * target paths, where the link paths are within the document root. Because
  36. * paths need to be normalized for this to work, use "//" to substitute
  37. * the doc root in the link paths (the array keys). E.g.:
  38. * <code>
  39. * array('//symlink' => '/real/target/path') // unix
  40. * array('//static' => 'D:\\staticStorage') // Windows
  41. * </code>
  42. *
  43. * 'docRoot': (default = $_SERVER['DOCUMENT_ROOT'])
  44. * see Minify_CSS_UriRewriter::rewrite
  45. *
  46. * @return string
  47. */
  48. public static function minify($css, $options = array())
  49. {
  50. $options = array_merge(array(
  51. 'compress' => true,
  52. 'removeCharsets' => true,
  53. 'currentDir' => null,
  54. 'docRoot' => $_SERVER['DOCUMENT_ROOT'],
  55. 'prependRelativePath' => null,
  56. 'symlinks' => array(),
  57. ), $options);
  58. if ($options['removeCharsets']) {
  59. $css = preg_replace('/@charset[^;]+;\\s*/', '', $css);
  60. }
  61. if ($options['compress']) {
  62. $obj = new CSSmin();
  63. $css = $obj->run($css);
  64. }
  65. if (! $options['currentDir'] && ! $options['prependRelativePath']) {
  66. return $css;
  67. }
  68. if ($options['currentDir']) {
  69. return Minify_CSS_UriRewriter::rewrite(
  70. $css
  71. ,$options['currentDir']
  72. ,$options['docRoot']
  73. ,$options['symlinks']
  74. );
  75. } else {
  76. return Minify_CSS_UriRewriter::prepend(
  77. $css
  78. ,$options['prependRelativePath']
  79. );
  80. }
  81. }
  82. }