Last active
October 11, 2022 13:08
-
-
Save divinity76/3902e53d9c0ecfbadc561de3191d1d6a to your computer and use it in GitHub Desktop.
php code scanner
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
use function var_dump as d; | |
$files = shell_exec("find . -name '*.php' -print0"); | |
$files = explode("\x00", rtrim($files, "\x00")); | |
foreach ($files as $file) { | |
echo "Checking {$file}..."; | |
if ($file === __FILE__) { | |
echo "skipping self\n"; | |
continue; | |
} | |
$contents = file_get_contents($file); | |
if (false === strpos($contents, 'ucfirst')) { | |
echo "skipping, no ucfirst\n"; | |
continue; | |
} | |
$phpNeedle = '<?php'; | |
$phpPos = strpos($contents, $phpNeedle); | |
if ($phpPos === false) { | |
echo "skipping, no {$phpNeedle}\n"; | |
continue; | |
} | |
$skipString = 'use function EasyAdGlobalFunctions\mb_ucfirst as ucfirst;'; | |
if (false !== strpos($contents, $skipString)) { | |
echo "skipping, {$skipString}\n"; | |
continue; | |
} | |
$phpPos = $phpPos + strlen($phpNeedle); | |
// now to avoid PHP Fatal error: strict_types declaration must be the very first statement in the script | |
if (1) { | |
$declareNeedleRex = '/declare\s*\(\s*strict_types\s*\=\s*\d+\s*\)\s*\;/'; | |
$matches = []; | |
if (preg_match($declareNeedleRex, $contents, $matches, PREG_OFFSET_CAPTURE)) { | |
$phpPos = $matches[0][1] + strlen($matches[0][0]); | |
} | |
} | |
// now to avoid PHP Fatal error: Namespace declaration statement has to be the very first statement or after any declare call in the script | |
if (1) { | |
$namespaceNeedleRex = '/^\s*namespace\s+[\w\\\\]+\s*\;/m'; | |
$matches = []; | |
if (preg_match($namespaceNeedleRex, $contents, $matches, PREG_OFFSET_CAPTURE)) { | |
$phpPos = $matches[0][1] + strlen($matches[0][0]); | |
} | |
} | |
$insertString = "\nuse function EasyAdGlobalFunctions\mb_ucfirst as ucfirst;"; | |
$pre = substr($contents, 0, $phpPos); | |
$post = substr($contents, $phpPos); | |
if (0 === strpos($post, ' extract')) { | |
$insertString = $insertString . "\n"; | |
} | |
$contents = $pre . $insertString . $post; | |
file_put_contents($file, $contents, LOCK_EX); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment