WP_Style_Engine_Processor::combine_rules_selectors │ private │ WP 6.1.0

Combines selectors from the rules store when they have the same styles.

Method of the class: WP_Style_Engine_Processor{}

No Hooks.

Returns

null. Nothing (null).

Usage

// private - for code of main (parent) class only
$result = $this->combine_rules_selectors();

Changelog

Since 6.1.0 Introduced.

WP_Style_Engine_Processor::combine_rules_selectors() code WP 7.1.2

private function combine_rules_selectors() {
	// Build an array of selectors along with the JSON-ified styles to make comparisons easier.
	$selectors_json = array();
	foreach ( $this->css_rules as $rule ) {
		$declarations        = $rule->get_declarations()->get_declarations();
		$declaration_options = $rule->get_declarations()->get_declaration_options();
		ksort( $declarations );
		// Declaration options are keyed by property and are part of the rule identity.
		ksort( $declaration_options );
		foreach ( $declaration_options as $property => $options ) {
			if ( is_array( $options ) ) {
				ksort( $options );
				$declaration_options[ $property ] = $options;
			}
		}
		$selectors_json[ $rule->get_selector() ] = wp_json_encode(
			array(
				'declarations'        => $declarations,
				'declaration_options' => $declaration_options,
			)
		);
	}

	// Combine selectors that have the same styles.
	foreach ( $selectors_json as $selector => $json ) {
		// Get selectors that use the same styles.
		$duplicates = array_keys( $selectors_json, $json, true );
		// Skip if there are no duplicates.
		if ( 1 >= count( $duplicates ) ) {
			continue;
		}

		$declarations = $this->css_rules[ $selector ]->get_declarations();

		foreach ( $duplicates as $key ) {
			// Unset the duplicates from the $selectors_json array to avoid looping through them as well.
			unset( $selectors_json[ $key ] );
			// Remove the rules from the rules collection.
			unset( $this->css_rules[ $key ] );
		}
		// Create a new rule with the combined selectors.
		$duplicate_selectors                     = implode( ',', $duplicates );
		$this->css_rules[ $duplicate_selectors ] = new WP_Style_Engine_CSS_Rule( $duplicate_selectors, $declarations );
	}
}