setSourceDir($sourceDir); $stripper->setTargetDir($targetDir); $stripper->strip(); class PhpSourceCodeStripper { public $sourceDir; public $targetDir; public function setSourceDir($dir) { if (!is_dir($dir)) { throw new Exception('Directory [' . $dir . '] does not exist'); } if (basename($dir) === '.' || basename($dir) === '..') { $dir = realpath($dir); } $this->sourceDir = rtrim($dir, DIRECTORY_SEPARATOR); } public function getSourceDir() { return $this->sourceDir; } public function setTargetDir($dir = null) { if (is_null($dir)) { $dir = $this->getSourceDir(); if (is_null($dir)) { throw new Exception('You must first call setSourceDir() before calling setTargetDir()'); } $dir .= '-stripped'; } $dir = rtrim($dir, DIRECTORY_SEPARATOR); if (!is_dir($dir)) { if (!mkdir($dir)) { throw new Exception('Cannot create directory [' . $dir . ']. Please create it manually and try again'); } } $this->targetDir = $dir; } public function getTargetDir() { return $this->targetDir; } public function strip($dir = null) { if (is_null($dir)) { $dir = $this->getSourceDir(); echo 'Source dir: ', $dir, "\n"; echo 'Target dir: ', $this->getTargetDir(), "\n\n"; } if (is_dir($dir)) { if ($handle = opendir($dir)) { while (($file = readdir($handle)) !== false) { // If $file is a directory and not . or .. if (is_dir($dir . DIRECTORY_SEPARATOR . $file) && $file !== '.' && $file !== '..') { if ($file !== '.svn') { // Dive deeper into the current dir $this->strip($dir . DIRECTORY_SEPARATOR . $file); } } elseif (is_file($dir . DIRECTORY_SEPARATOR . $file)) { if (substr($file, strrpos($file, '.')) === '.php') { $targetDir = str_replace($this->getSourceDir(), $this->getTargetDir(), $dir); if (!is_dir($targetDir) && !mkdir($targetDir, 0777, true)) { throw new Exception('Cannot create directory [' . $targetDir . ']. Please make sure the parent dir [' . $this->getTargetDir() . '] has write permissions'); } $strippedData = php_strip_whitespace($dir . DIRECTORY_SEPARATOR . $file); if ($strippedData !== '') { if (strpos($strippedData, '<<<') === false) { echo 'Stripping: ', $dir . DIRECTORY_SEPARATOR . $file; $this->writeFile($targetDir . DIRECTORY_SEPARATOR . $file, $strippedData); $sourceFilesize = filesize($dir . DIRECTORY_SEPARATOR . $file); $targetFilesize = strlen($strippedData); echo ' ', $sourceFilesize, ' bytes -> ', $targetFilesize, ' bytes', ' = ', 100 - round(100 / $sourceFilesize * $targetFilesize, 0), "% smaller\n"; } else { echo 'Heredoc detected! Copying: ', $dir . DIRECTORY_SEPARATOR . $file, "\n"; copy($dir . DIRECTORY_SEPARATOR . $file, $targetDir . DIRECTORY_SEPARATOR . $file); } } } } } closedir($handle); } } } public function writeFile($filename, $data) { if (!$handle = fopen($filename, 'w')) { echo "Cannot open file ($filename)"; exit; } if (fwrite($handle, $data) === false) { echo "Cannot write to file ($filename)"; exit; } fclose($handle); } }