noComment = $noComment; } public function clear () { $this->files = array(); return $this; } public function addFile ( $file, $mode = '', $mirror = null ) { if ( !file_exists($file) ) throw new Exception(sprintf('"%1$s" is not a file or does not exist !', $file)); $content = $this->filter($file, array_filter(preg_split('!\s++!', $mode)), $this->noComment); $this->files[] = array( 'file' => $file, 'content' => $content, ); if ( $mirror ) $this->writeFile($mirror, $content); return $this; } public function addFiles ( $files ) { foreach ( $files as $file => $mode ) $this->addFile($file, $mode); return $this; } public function process ( $noComment = false ) { $str = ''; foreach ( $this->files as $file => $mode ) $str .= "\n" . self::filter($file, $mode, $noComment); return $this; } public function writeFile ( $file, $content ) { if ( !file_exists(dirname($file)) ) throw new Exception(sprintf('The directory for file "%1$s" does not exist !', $file)); file_put_contents($file, ""); return $this; } public function toFile ( $file ) { if ( !file_exists(dirname($file)) ) throw new Exception(sprintf('The directory for file "%1$s" does not exist !', $file)); $content = ''; foreach ( $this->files as $fileContent ) $content .= $fileContent['content']; file_put_contents($file, ""); return $this; } static private function filter ( $file, $mode, $noComment = false ) { $commentTokens = array(T_OPEN_TAG, T_CLOSE_TAG); if ( $noComment ) { $commentTokens[] = T_COMMENT; $commentTokens[] = T_DOC_COMMENT; } $m = array(); $state = ''; $str = ''; foreach ( token_get_all(file_get_contents($file)) as $token ) { if ( !empty($token[0]) && $token[0] === T_DIR ) $token = sprintf('"%1$s"', realpath(dirname($file))); if ( !$state ) { if ( $token[0] === T_COMMENT && preg_match('!^/\*\#BEGIN\s++((\!?)([a-zA-Z0-9]++))\s*\#\*/$!', $token[1], $m) && ( ( !in_array($m[3], $mode) && !$m[2] ) || ( in_array($m[3], $mode) && $m[2] ) ) ) { $state = $m[1]; if ( !$noComment ) $str .= $token[1]; } elseif ( !is_array($token) ) $str .= $token; elseif ( !in_array($token[0], $commentTokens) ) $str .= $token[1]; } elseif ( $token[0] === T_COMMENT ) { if ( preg_match('!^/\*\#END\s++((\!?)([a-zA-Z0-9]++))\s*\#\*/$!', $token[1], $m) ) if ( $m[1] == $state ) { if ( !$noComment ) $str .= $token[1]; $state = ''; } } elseif ( !$noComment ) $str .= str_repeat("\n", count(preg_split("!\n!", is_array($token) ? $token[1] : $token)) - 1); } return $str; } } ?>