Topological Sort / Dependency resolver in PHP