Skip to content

Instantly share code, notes, and snippets.

@divinity76
Last active October 11, 2022 13:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save divinity76/3902e53d9c0ecfbadc561de3191d1d6a to your computer and use it in GitHub Desktop.
Save divinity76/3902e53d9c0ecfbadc561de3191d1d6a to your computer and use it in GitHub Desktop.
php code scanner
<?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