Skip to content
Advertisement

PHP topological sort

LIST: controller name => priority:required controllers

JavaScript

sorted and expected output:

JavaScript

First sort by priority, then reorder based on required controllers to be loaded before. ensure not to be stuck in an infinite loop due to controllers requiring each other.


I assume I’ll need something like this:

JavaScript

Please help solve this with these steps:

  1. Remove infinite loop controllers (ex: controller_loopexit1 & controller_loopexit2)
  2. Remove controllers that have a dependency of a controller that doesn`t exist (ex: controller_x depending on controller_not_exists.)
  3. Sort remaining items by priority number, lowest comes first
  4. Second sort by dependencies

Advertisement

Answer

Code:

JavaScript

Usage:

  1. I am using https://github.com/marcj/topsort.php. To use it you must have Composer. Run composer require marcj/topsort to install the code dependency.
  2. That’s it. In case of an exception, the code does not automatically remove the nodes (controllers), it’s best to use human intervention to make sure you resolve those exceptions and have a proper input.

Examples:

Case 1

Input (Your Original Input – Missing Dependency):

JavaScript

Output:

JavaScript

Case 2

Input (Add the missing dependency, you still have circular-dependency/infinite-loop):

JavaScript

Output:

JavaScript

Case 3

Input (Removed the controllers with circular dependency):

JavaScript

Output:

JavaScript

Case 4

Input (Removed controller_not_exists and controller_x):

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement