Skip to content

Instantly share code, notes, and snippets.

@dutymess
Forked from meysampg/zeshter.php
Last active July 12, 2019 20:04
Show Gist options
  • Save dutymess/3263031630f355a55a28cf4c30596517 to your computer and use it in GitHub Desktop.
Save dutymess/3263031630f355a55a28cf4c30596517 to your computer and use it in GitHub Desktop.
Zeshter function remove all comments and docblocks from a given php file or a folder of php files.
#!/usr/bin/env php
<?php
/**
* Zeshter function remove all comments and docblocks from a given
* php file or a folder of php files. Yep, it just mirine into file.
*
* @param string|null $path path of a php file or a folder contains php files
*/
function zeshter(?string $path, bool $debugMode = false)
{
debug("\e[1;34mParsing \e[0;35m{$path}\e[0m...\n", $debugMode);
if (file_exists($path)) {
if (is_dir($path)) {
debug("\e[1;34mParsing directory \e[0;35m{$path}\e[0m...\n", $debugMode);
$folderContents = opendir($path);
while (false !== ($file = readdir($folderContents))) {
if (!in_array($file, [".", ".."])) {
zeshter($path . DIRECTORY_SEPARATOR . $file, $debugMode);
}
}
closedir($folderContents);
debug("\e[1;34mParsing directory \e[0;35m{$path}\e[0m Completed.\n", $debugMode);
} elseif (is_file($path) && 'php' == pathinfo($path, PATHINFO_EXTENSION)) {
$fileContents = file_get_contents($path);
$newfileContents = '';
// list of tokens: http://php.net/manual/en/tokens.php
$toRemoveTokens = [T_COMMENT, T_DOC_COMMENT];
$tokens = token_get_all($fileContents);
foreach ($tokens as $token) { // 0: numeric equivallent of token, 1: string value of token
if (is_array($token)) {
if (in_array($token[0], $toRemoveTokens)) { // you cannot always remove someone, just by ignoring them. ;)
$lines = substr_count($token[1], "\n");
$newfileContents .= str_repeat("\n", $lines);
continue;
}
$newfileContents .= $token[1];
} else {
$newfileContents .= $token;
}
}
file_put_contents($path, $newfileContents);
}
} else {
die("\e[0;31m{$path} does not exists. Please check the path and try again.\e[0m\n");
}
debug("\e[1;34mParsing \e[0;35m{$path}\e[0m Completed.\n", $debugMode);
}
/**
* printout the debug data
*
* @param string $s data to show
* @param bool $on indicate that data must be shown or not
*/
function debug(string $s, bool $on = false)
{
if ($on) {
echo $s;
}
}
$debug = false;
if (!isset($argv[1])) {
die("Please use program in \e[0;31m{$argv[0]} \e[0;36mdirectory\e[0m format (\e[0;36mdirectory\e[0m is path of folder).\n");
}
if (isset($argv[2])) {
$debug = true;
}
zeshter($argv[1], $debug);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment