Skip to content

Instantly share code, notes, and snippets.

@meysampg
Last active October 10, 2019 09:05
Show Gist options
  • Save meysampg/3230c0236c60d134912aad5d7e1e0762 to your computer and use it in GitHub Desktop.
Save meysampg/3230c0236c60d134912aad5d7e1e0762 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 can remove someone, just by ignoring him ;)
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);
@ImperatorMarsa
Copy link

Спасибулички дядь. Мне не пришлось изобретать велосипед, чтобы почистить перед релизом свой код.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment