<?php
/**
* Resolves dependencies of collections for quick fixes with synchronous execution.
*
* @param array $collections An array of collections, where each collection is an array of items.
* @return array An array of resolved collections. Returns an empty array if dependencies cannot be resolved.
*/
function resolveDependencies(array $collections): array
{
$resolvedCollections = [];
$dependencies = []; // Maps collection key to its dependencies (keys of other collections)
// Build dependency map
foreach ($collections as $collectionKey => $collection) {
$dependencies[$collectionKey] = [];
foreach ($collection as $item) {
// Example: Item "A" depends on item "B" in another collection
if (isset($item['depends_on'])) {
$dependencies[$collectionKey][] = $item['depends_on'];
}
}
}
$resolved = []; // Keep track of collections that have been resolved.
// Recursive function to resolve a collection
function resolveCollection(string $collectionKey, array &$collections, array &$resolved): bool
{
if (in_array($collectionKey, $resolved)) {
return true; // Already resolved
}
$collection = $collections[$collectionKey];
$resolvedCollections[$collectionKey] = $collection; // Store the collection
foreach ($collection as $item) {
if (isset($item['depends_on'])) {
$dependencyKey = $item['depends_on'];
if (!isset($collections[$dependencyKey])) {
// Dependency collection not found
error_log("Dependency collection not found: " . $dependencyKey);
return false;
}
if (!resolveCollection($dependencyKey, $collections, $resolved)) {
return false; // Dependency resolution failed
}
}
}
return true; // Collection and its dependencies are resolved
}
// Resolve each collection
foreach ($collections as $collectionKey => $collection) {
if (!resolveCollection($collectionKey, $collections, $resolved)) {
return []; // Return empty array if any dependency fails
}
}
return $resolvedCollections;
}
//Example usage
if(count($argv) > 1) {
$collections = [
'collection1' => [
['name' => 'A'],
['name' => 'B']
],
'collection2' => [
['name' => 'C', 'depends_on' => 'collection1'],
['name' => 'D', 'depends_on' => 'collection1']
],
'collection3' => [
['name' => 'E', 'depends_on' => 'collection2']
]
];
$resolved = resolveDependencies($collections);
if(!empty($resolved)) {
print_r($resolved);
} else {
echo "Dependency resolution failed.\n";
}
} else {
echo "Usage: php script.php\n";
}
?>
Add your comment