WP_Plugin_Dependencies::check_for_circular_dependencies( array $dependents, array $dependencies ): array

In this article

Checks for circular dependencies.

Parameters

$dependentsarrayrequired
Array of dependent plugins.
$dependenciesarrayrequired
Array of plugins dependencies.

Return

array A circular dependency pairing, or an empty array if none exists.

Source

protected static function check_for_circular_dependencies( $dependents, $dependencies ) {
	$circular_dependencies_pairs = array();

	// Check for a self-dependency.
	$dependents_location_in_its_own_dependencies = array_intersect( $dependents, $dependencies );
	if ( ! empty( $dependents_location_in_its_own_dependencies ) ) {
		foreach ( $dependents_location_in_its_own_dependencies as $self_dependency ) {
			self::$circular_dependencies_slugs[] = $self_dependency;
			$circular_dependencies_pairs[]       = array( $self_dependency, $self_dependency );

			// No need to check for itself again.
			unset( $dependencies[ array_search( $self_dependency, $dependencies, true ) ] );
		}
	}

	/*
	 * Check each dependency to see:
	 * 1. If it has dependencies.
	 * 2. If its list of dependencies includes one of its own dependents.
	 */
	foreach ( $dependencies as $dependency ) {
		// Check if the dependency is also a dependent.
		$dependency_location_in_dependents = array_search( $dependency, self::$dependent_slugs, true );

		if ( false !== $dependency_location_in_dependents ) {
			$dependencies_of_the_dependency = self::$dependencies[ $dependency_location_in_dependents ];

			foreach ( $dependents as $dependent ) {
				// Check if its dependencies includes one of its own dependents.
				$dependent_location_in_dependency_dependencies = array_search(
					$dependent,
					$dependencies_of_the_dependency,
					true
				);

				if ( false !== $dependent_location_in_dependency_dependencies ) {
					self::$circular_dependencies_slugs[] = $dependent;
					self::$circular_dependencies_slugs[] = $dependency;
					$circular_dependencies_pairs[]       = array( $dependent, $dependency );

					// Remove the dependent from its dependency's dependencies.
					unset( $dependencies_of_the_dependency[ $dependent_location_in_dependency_dependencies ] );
				}
			}

			$dependents[] = $dependency;

			/*
			 * Now check the dependencies of the dependency's dependencies for the dependent.
			 *
			 * Yes, that does make sense.
			 */
			$circular_dependencies_pairs = array_merge(
				$circular_dependencies_pairs,
				self::check_for_circular_dependencies( $dependents, array_unique( $dependencies_of_the_dependency ) )
			);
		}
	}

	return $circular_dependencies_pairs;
}

Changelog

VersionDescription
6.5.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.