WP_Script_Modules::sort_item_dependenciesprivateWP 6.9.0

Recursively sorts the dependencies for a single script module identifier.

Method of the class: WP_Script_Modules{}

No Hooks.

Returns

true|false. True on success, false on failure (e.g., missing dependency).

Usage

// private - for code of main (parent) class only
$result = $this->sort_item_dependencies( $id, $import_types, $sorted ): bool;
$id(string) (required)
The identifier of the script module to sort.
$import_types(string[]) (required)
Import types of dependencies to retrieve: 'static', 'dynamic', or both.
$sorted(array) (required)
.

Changelog

Since 6.9.0 Introduced.

WP_Script_Modules::sort_item_dependencies() code WP 7.0.2

private function sort_item_dependencies( string $id, array $import_types, array &$sorted ): bool {
	// If already processed, don't do it again.
	if ( in_array( $id, $sorted, true ) ) {
		return true;
	}

	// If the item doesn't exist, fail.
	if ( ! isset( $this->registered[ $id ] ) ) {
		return false;
	}

	$dependency_ids = array();
	foreach ( $this->registered[ $id ]['dependencies'] as $dependency ) {
		if ( in_array( $dependency['import'], $import_types, true ) ) {
			$dependency_ids[] = $dependency['id'];
		}
	}

	// If the item requires dependencies that do not exist, fail.
	$missing_dependencies = array_diff( $dependency_ids, array_keys( $this->registered ) );
	if ( count( $missing_dependencies ) > 0 ) {
		if ( ! in_array( $id, $this->modules_with_missing_dependencies, true ) ) {
			_doing_it_wrong(
				get_class( $this ) . '::register',
				sprintf(
					/* translators: 1: Script module ID, 2: List of missing dependency IDs. */
					__( 'The script module with the ID "%1$s" was enqueued with dependencies that are not registered: %2$s.' ),
					$id,
					implode( wp_get_list_item_separator(), $missing_dependencies )
				),
				'6.9.1'
			);
			$this->modules_with_missing_dependencies[] = $id;
		}

		return false;
	}

	// Recursively process dependencies.
	foreach ( $dependency_ids as $dependency_id ) {
		if ( ! $this->sort_item_dependencies( $dependency_id, $import_types, $sorted ) ) {
			// A dependency failed to resolve, so this branch fails.
			return false;
		}
	}

	// All dependencies are sorted, so we can now add the current item.
	$sorted[] = $id;

	return true;
}