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