diff --git a/lib/Doctrine/ORM/Internal/TopologicalSort.php b/lib/Doctrine/ORM/Internal/TopologicalSort.php index 2bf1624ced8..9f9f8c52852 100644 --- a/lib/Doctrine/ORM/Internal/TopologicalSort.php +++ b/lib/Doctrine/ORM/Internal/TopologicalSort.php @@ -129,7 +129,7 @@ private function visit(int $oid): void $this->states[$oid] = self::IN_PROGRESS; // Continue the DFS downwards the edge list - foreach ($this->edges[$oid] as $adjacentId => $optional) { + foreach (array_reverse($this->edges[$oid], true) as $adjacentId => $optional) { try { $this->visit($adjacentId); } catch (CycleDetectedException $exception) { diff --git a/tests/Doctrine/Tests/ORM/Internal/TopologicalSortTest.php b/tests/Doctrine/Tests/ORM/Internal/TopologicalSortTest.php index bba00d2d44e..b94d8070f6c 100644 --- a/tests/Doctrine/Tests/ORM/Internal/TopologicalSortTest.php +++ b/tests/Doctrine/Tests/ORM/Internal/TopologicalSortTest.php @@ -153,6 +153,28 @@ public function testNodesMaintainOrderWhenNoDepencency(): void self::assertSame(['A', 'B', 'C'], $this->computeResult()); } + public function testNodesMaintainOrderWhenEdgesPermit(): void + { + $this->addNodes('A', 'B', 'C'); + $this->addEdge('A', 'B'); + $this->addEdge('A', 'C'); + + // Nodes shall maintain the order in which they were added + // when permitted by edges/constraints + self::assertSame(['A', 'B', 'C'], $this->computeResult()); + } + + public function testNodesMaintainOrderWhenEdgesPermitAndMainNodePersistedLast(): void + { + $this->addNodes('B', 'C', 'A'); + $this->addEdge('A', 'B'); + $this->addEdge('A', 'C'); + + // Nodes shall maintain the order in which they were added + // when permitted by edges/constraints + self::assertSame(['A', 'B', 'C'], $this->computeResult()); + } + public function testDetectSmallCycle(): void { $this->addNodes('A', 'B');