8 * Add line numbers in C-style comments for easier debugging of combined content
11 * @author Stephen Clay <steve@mrclay.org>
12 * @author Adam Pedersen (Issue 55 fix)
17 * Add line numbers in C-style comments
19 * This uses a very basic parser easily fooled by comment tokens inside
20 * strings or regexes, but, otherwise, generally clean code will not be
21 * mangled. URI rewriting can also be performed.
23 * @param string $content
25 * @param array $options available options:
27 * 'id': (optional) string to identify file. E.g. file name/path
29 * 'currentDir': (default null) if given, this is assumed to be the
\r
30 * directory of the current CSS file. Using this, minify will rewrite
\r
31 * all relative URIs in import/url declarations to correctly point to
\r
32 * the desired files, and prepend a comment with debugging information about
37 public static function minify($content, $options = array())
39 $id = (isset($options['id']) && $options['id'])
42 $content = str_replace("\r\n", "\n", $content);
43 $lines = explode("\n", $content);
44 $numLines = count($lines);
45 // determine left padding
46 $padTo = strlen($numLines);
50 while (null !== ($line = array_shift($lines))) {
51 if (('' !== $id) && (0 == $i % 50)) {
52 array_push($newLines, '', "/* {$id} */", '');
55 $newLines[] = self::_addNote($line, $i, $inComment, $padTo);
56 $inComment = self::_eolInComment($line, $inComment);
58 $content = implode("\n", $newLines) . "\n";
60 // check for desired URI rewriting
61 if (isset($options['currentDir'])) {
62 require_once 'Minify/CSS/UriRewriter.php';
63 Minify_CSS_UriRewriter::$debugText = '';
64 $content = Minify_CSS_UriRewriter::rewrite(
66 ,$options['currentDir']
67 ,isset($options['docRoot']) ? $options['docRoot'] : $_SERVER['DOCUMENT_ROOT']
\r
68 ,isset($options['symlinks']) ? $options['symlinks'] : array()
70 $content = "/* Minify_CSS_UriRewriter::\$debugText\n\n"
71 . Minify_CSS_UriRewriter::$debugText . "*/\n"
79 * Is the parser within a C-style comment at the end of this line?
81 * @param string $line current line of code
83 * @param bool $inComment was the parser in a comment at the
84 * beginning of the line?
88 private static function _eolInComment($line, $inComment)
90 while (strlen($line)) {
94 $pos = strpos($line, $search);
100 ? substr($line, $pos, 3)
101 : substr($line, $pos-1, 3)) != '*/*')
103 $inComment = ! $inComment;
105 $line = substr($line, $pos + 2);
112 * Prepend a comment (or note) to the given line
114 * @param string $line current line of code
116 * @param string $note content of note/comment
118 * @param bool $inComment was the parser in a comment at the
119 * beginning of the line?
121 * @param int $padTo minimum width of comment
125 private static function _addNote($line, $note, $inComment, $padTo)
128 ? '/* ' . str_pad($note, $padTo, ' ', STR_PAD_RIGHT) . ' *| ' . $line
129 : '/* ' . str_pad($note, $padTo, ' ', STR_PAD_RIGHT) . ' */ ' . $line;