Skip to content

Instantly share code, notes, and snippets.

@Yousha
Created April 7, 2025 06:22
Show Gist options
  • Save Yousha/245c1db14e319efc84efadd7ad0fdd48 to your computer and use it in GitHub Desktop.
Save Yousha/245c1db14e319efc84efadd7ad0fdd48 to your computer and use it in GitHub Desktop.
Scans a directory (excluding `vendor`) for `.php` files and identifies used PHP extensions.
<?php
declare(strict_types=1);
error_reporting(E_ALL);
/**
* Recursively scans a directory for PHP files while ignoring the "vendor" folder.
*
* @param string $directory The directory to scan.
* @return array An array of file paths for all found PHP files.
*/
function getPhpFiles(string $directory): array
{
$files = [];
$iterator = new RecursiveIteratorIterator(
new RecursiveCallbackFilterIterator(
new RecursiveDirectoryIterator($directory, FilesystemIterator::SKIP_DOTS),
function ($current) {
return !($current->isDir() && basename($current->getPathname()) === 'vendor'); // Skip vendor folder.
}
),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($iterator as $file) {
if ($file->isFile() && $file->getExtension() === 'php') {
$files[] = $file->getPathname();
}
}
return $files;
}
/**
* Extracts a list of PHP extensions used in the provided PHP files.
*
* This function scans for function calls that belong to installed extensions.
*
* @param array $files An array of PHP file paths to scan.
* @return array A unique list of detected PHP extensions.
*/
function extractUsedExtensions(array $files): array
{
$extensions = [];
$extensionFunctions = [];
// Get all available PHP extensions and their functions.
foreach (get_loaded_extensions() as $ext) {
foreach (get_extension_funcs($ext) ?: [] as $func) {
$extensionFunctions[$func] = $ext;
}
}
foreach ($files as $file) {
$content = file_get_contents($file);
foreach ($extensionFunctions as $func => $ext) {
if (preg_match("/\b$func\s*\(/i", $content)) {
$extensions[] = $ext;
}
}
}
return array_unique($extensions);
}
$directory = !empty($argv[1]) ? $argv[1] : __DIR__;
$phpFiles = getPhpFiles($directory);
$usedExtensions = extractUsedExtensions($phpFiles);
echo PHP_EOL;
echo "Target path: $directory" . PHP_EOL;
echo "Used PHP extensions:" . PHP_EOL;
foreach ($usedExtensions as $extension) {
echo "* $extension" . PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment