<?php
/**
* Recursively validates file structures with memory optimization.
*
* @param string $root The root directory to validate.
* @param array $expected_structure An array defining the expected file/directory structure.
* @param array $validated_structure An array to store the validated structure.
* @param int $level The current level of recursion (for debugging/logging).
* @return bool True if the structure is valid, false otherwise.
*/
function validateFileStructureRecursive(string $root, array $expected_structure, array &$validated_structure, int $level = 0): bool
{
// Check if the root directory exists
if (!is_dir($root)) {
error_log("Error: Root directory '$root' does not exist.");
return false;
}
// Initialize validated structure if it's not already
if (!isset($validated_structure[$root])) {
$validated_structure[$root] = [];
}
// Iterate through the expected structure.
foreach ($expected_structure as $item => $expected_type) {
$full_path = $root . '/' . $item;
// Check if the item exists.
if (!is_dir($full_path) && !file_exists($full_path)) {
error_log("Error: Expected item '$item' not found at '$full_path'.");
return false;
}
//Validate based on expected type.
if ($expected_type == 'directory') {
//If it's a directory, recursively call the function.
if (!is_dir($full_path)) {
error_log("Error: '$full_path' is not a directory, but expected one.");
return false;
}
if (!validateFileStructureRecursive($full_path, $expected_structure, $validated_structure, $level + 1)) {
return false;
}
} elseif ($expected_type == 'file') {
// Check if it's a file.
if (!file_exists($full_path)) {
error_log("Error: Expected file '$full_path' not found.");
return false;
}
if (is_dir($full_path)) {
error_log("Error: '$full_path' is a directory, but expected a file.");
return false;
}
} else {
error_log("Error: Invalid expected type '$expected_type' for item '$item'.");
return false;
}
}
//Add the validated structure to the main validated structure
$validated_structure[$root] = $validated_structure[$root] ?? [];
return true;
}
/**
* Main function to call the validation process.
*
* @param string $root The root directory to validate.
* @param array $expected_structure An array defining the expected file/directory structure.
* @return bool True if the structure is valid, false otherwise.
*/
function validateStructure(string $root, array $expected_structure): bool
{
$validated_structure = []; //Initialize the validated structure.
return validateFileStructureRecursive($root, $expected_structure, $validated_structure);
}
//Example Usage:
/*
$expected_structure = [
'src' => 'directory',
'src/main.php' => 'file',
'src/helpers' => 'directory',
'src/helpers/utils.php' => 'file',
'tests' => 'directory',
];
$root_directory = './my_project'; // Replace with your project root.
if (validateStructure($root_directory, $expected_structure)) {
echo "File structure is valid.\n";
} else {
echo "File structure is invalid.\n";
}
*/
?>
Add your comment