Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save MisterDaniels/b30c9e59bfe6091302aefad895ddee59 to your computer and use it in GitHub Desktop.
Save MisterDaniels/b30c9e59bfe6091302aefad895ddee59 to your computer and use it in GitHub Desktop.
<?php
$CONCATENATED_QUERIES_REGEX = '/(SELECT|UPDATE|INSERT\s+INTO|DELETE\s+FROM)\s+[^;|\)]*[\'"]\s*\.\s*\$[a-zA-Z_]\w*/';
function scanDirectory($dir) {
$files = [];
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach($iterator as $file) {
if ($file->isFile() && $file->getExtension() === 'php') {
$fileLocation = $file->getPathname();
if (strpos($fileLocation, 'node_modules') || strpos($fileLocation, 'vendor')) continue;
$files[] = $file->getPathname();
}
}
return $files;
}
function getRegexMatchesInSource($files, $regex) {
$scannedFiles = [];
foreach($files as $file) {
$content = file_get_contents($file);
if (preg_match_all($regex, $content, $matches, PREG_OFFSET_CAPTURE)) {
foreach($matches[0] as $match) {
$line = getLineNumber($content, $match[1]);
$scannedFiles[] = "$file:$line";
}
}
}
return $scannedFiles;
}
function getLineNumber($content, $offset) {
$substr = substr($content, 0, $offset);
return substr_count($substr, "\n") + 1;
}
if ($argc < 2) {
echo "Use: php concatenated_queries_validator.php <directory>\n";
exit(1);
}
$directory = $argv[1];
if (!is_dir($directory)) {
echo "Directory not found: $directory\n";
exit(1);
}
$files = scanDirectory($directory);
$scannedFiles = getRegexMatchesInSource($files, $CONCATENATED_QUERIES_REGEX);
foreach($scannedFiles as $file) {
echo "$file\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment