-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdependencies.php
More file actions
92 lines (73 loc) · 1.96 KB
/
dependencies.php
File metadata and controls
92 lines (73 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
/**
* Sort dependencies
*
* This class sorts dependencies, this can be whatever.
* The sorting algorithm used is @see http://en.wikipedia.org/wiki/Topological_sorting
*/
class Dependencies {
public $sources = array();
public function __construct() {
}
/**
* Add source
* @param {String} name Name of file
* @param {Array} dependencies
*/
public function add($name, $dependencies = array()) {
// If dependencies is a string, split into array
if(gettype($dependencies) == 'string') {
$dependencies = preg_split('/,\s?/', $dependencies);
}
// Add
$this -> sources[$name] = (object) array(
'name' => $name,
'dependencies' => (array) $dependencies
);
}
/**
* Visit node, used in sorting
*
* This function checks all the dependencies of a node and calls
* this function for each of them
*/
private function visit($source, &$sources, &$sorted) {
// If source has not been visited
if (!$source -> visited) {
// Set that source has been visited
$source -> visited = true;
// Check each dependency
foreach($source -> dependencies as $dependency) {
// Call this function for each source
if(isset($sources[$dependency])) {
$this -> visit($sources[$dependency], $sources, $sorted);
} else {
exit(sprintf("The source '%s' depends on '%s' but there are no source with that name", $source -> name, $dependency) . PHP_EOL);
}
}
// Add source to sorted array
$sorted[] = $source;
}
}
/**
* Sort dependencies and return array with sorted sources
*
* @returns {Array} Sorted sources as array
*/
public function sort() {
$sources = $this -> sources;
$sorted = array();
// Reset visited
foreach($sources as $source) {
$source -> visited = false;
}
// Loop through each source
foreach($sources as $source) {
// Set visited to true
$this -> visit($source, $sources, $sorted);
}
// Just return sources
return $sorted;
}
}
?>