CommentPreserver.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /**
  3. * Class Minify_CommentPreserver
  4. * @package Minify
  5. */
  6. /**
  7. * Process a string in pieces preserving C-style comments that begin with "/*!"
  8. *
  9. * @package Minify
  10. * @author Stephen Clay <steve@mrclay.org>
  11. */
  12. class Minify_CommentPreserver {
  13. /**
  14. * String to be prepended to each preserved comment
  15. *
  16. * @var string
  17. */
  18. public static $prepend = "\n";
  19. /**
  20. * String to be appended to each preserved comment
  21. *
  22. * @var string
  23. */
  24. public static $append = "\n";
  25. /**
  26. * Process a string outside of C-style comments that begin with "/*!"
  27. *
  28. * On each non-empty string outside these comments, the given processor
  29. * function will be called. The comments will be surrounded by
  30. * Minify_CommentPreserver::$preprend and Minify_CommentPreserver::$append.
  31. *
  32. * @param string $content
  33. * @param callback $processor function
  34. * @param array $args array of extra arguments to pass to the processor
  35. * function (default = array())
  36. * @return string
  37. */
  38. public static function process($content, $processor, $args = array())
  39. {
  40. $ret = '';
  41. while (true) {
  42. list($beforeComment, $comment, $afterComment) = self::_nextComment($content);
  43. if ('' !== $beforeComment) {
  44. $callArgs = $args;
  45. array_unshift($callArgs, $beforeComment);
  46. $ret .= call_user_func_array($processor, $callArgs);
  47. }
  48. if (false === $comment) {
  49. break;
  50. }
  51. $ret .= $comment;
  52. $content = $afterComment;
  53. }
  54. return $ret;
  55. }
  56. /**
  57. * Extract comments that YUI Compressor preserves.
  58. *
  59. * @param string $in input
  60. *
  61. * @return array 3 elements are returned. If a YUI comment is found, the
  62. * 2nd element is the comment and the 1st and 3rd are the surrounding
  63. * strings. If no comment is found, the entire string is returned as the
  64. * 1st element and the other two are false.
  65. */
  66. private static function _nextComment($in)
  67. {
  68. if (
  69. false === ($start = strpos($in, '/*!'))
  70. || false === ($end = strpos($in, '*/', $start + 3))
  71. ) {
  72. return array($in, false, false);
  73. }
  74. $ret = array(
  75. substr($in, 0, $start)
  76. ,self::$prepend . '/*!' . substr($in, $start + 3, $end - $start - 1) . self::$append
  77. );
  78. $endChars = (strlen($in) - $end - 2);
  79. $ret[] = (0 === $endChars)
  80. ? ''
  81. : substr($in, -$endChars);
  82. return $ret;
  83. }
  84. }