Skip to content
docsv0.8.0

TopologicalSorter

Orders a set of nodes so that every dependency precedes its dependents (Kahn's algorithm). A generic, dependency-free graph utility: the caller supplies the node set and the directed edges, and gets back the nodes in a valid topological order (dependency-first). Edges that reference nodes outside the given set are ignored, so a partial graph sorts cleanly.

TopologicalSorter::sort()

public function sort(array $nodes, array $edges): array

Orders the nodes so that every dependency comes out before its dependents. Ties keep the order the caller gave, so the same graph always sorts the same way: a boot order that varies between runs turns an ordering bug into one that shows up once in three runs and never while anyone is watching.

Parameters

Parameters of sort()
NameTypeDescription
$nodeslist<string>Node names to order.
$edgeslist<array{0: string, 1: string}>`[dependency, dependent]` pairs — the dependency must come before the dependent. Edges referencing a node outside `$nodes` are ignored.

Returns

The nodes in dependency-first topological order.

Throws

RuntimeException If the graph contains a cycle.