1. <?php
  2. /**
  3. * Resolves dependencies of text files.
  4. *
  5. * @param array $files An array of file paths.
  6. * @return array An associative array where keys are file paths and values are arrays of dependencies.
  7. * Returns an empty array if input is invalid.
  8. */
  9. function resolveDependencies(array $files): array
  10. {
  11. if (empty($files)) {
  12. return []; // Handle empty input
  13. }
  14. $dependencies = [];
  15. $fileMap = [];
  16. // Build a map of files to their content and dependency information.
  17. foreach ($files as $filePath) {
  18. if (!file_exists($filePath)) {
  19. error_log("File not found: " . $filePath); // Log missing file
  20. continue; // Skip to the next file
  21. }
  22. $fileContent = file_get_contents($filePath);
  23. $fileMap[$filePath] = [
  24. 'content' => $fileContent,
  25. 'dependencies' => [],
  26. ];
  27. // Extract dependencies from the file content. This example assumes a simple "requires:" format.
  28. preg_match_all('/requires:\s*([\w\s,]+)/', $fileContent, $matches);
  29. if (!empty($matches[1])) {
  30. $dependencies[$filePath] = explode(',', trim(str_replace(' ', '', $matches[1][0]))); // Split dependencies by comma
  31. }
  32. }
  33. // Resolve dependencies recursively.
  34. foreach ($fileMap as $filePath => $fileInfo) {
  35. foreach ($fileInfo['dependencies'] as $dependencyPath) {
  36. if (isset($fileMap[$dependencyPath])) {
  37. // Dependency exists, add it to the current file's dependencies
  38. $fileInfo['dependencies'][] = $dependencyPath;
  39. } else {
  40. // Dependency doesn't exist, log an error.
  41. error_log("Dependency not found: " . $dependencyPath . " for file: " . $filePath);
  42. }
  43. }
  44. }
  45. return $dependencies;
  46. }
  47. //Example usage (can be removed for production)
  48. /*
  49. $files = [
  50. 'file1.txt',
  51. 'file2.txt',
  52. 'file3.txt'
  53. ];
  54. //Create dummy files for testing
  55. file_put_contents('file1.txt', 'This is file 1. requires: file2, file3');
  56. file_put_contents('file2.txt', 'This is file 2. requires: file3');
  57. file_put_contents('file3.txt', 'This is file 3.');
  58. $resolvedDependencies = resolveDependencies($files);
  59. print_r($resolvedDependencies);
  60. //Clean up dummy files
  61. unlink('file1.txt');
  62. unlink('file2.txt');
  63. unlink('file3.txt');
  64. */
  65. ?>

Add your comment