WP_Interactivity_API::extract_directive_value()privateWP 6.5.0

Parses and extracts the namespace and reference path from the given directive attribute value.

If the value doesn't contain an explicit namespace, it returns the default one. If the value contains a JSON object instead of a reference path, the function tries to parse it and return the resulting array. If the value contains strings that represent booleans ("true" and "false"), numbers ("1" and "1.2") or "null", the function also transform them to regular booleans, numbers and null.

Example:

extract_directive_value( 'actions.foo', 'myPlugin' )                      => array( 'myPlugin', 'actions.foo' )
extract_directive_value( 'otherPlugin::actions.foo', 'myPlugin' )         => array( 'otherPlugin', 'actions.foo' )
extract_directive_value( '{ "isOpen": false }', 'myPlugin' )              => array( 'myPlugin', array( 'isOpen' => false ) )
extract_directive_value( 'otherPlugin::{ "isOpen": false }', 'myPlugin' ) => array( 'otherPlugin', array( 'isOpen' => false ) )

Method of the class: WP_Interactivity_API{}

No Hooks.

Return

Array. An array containing the namespace in the first item and the JSON, the reference path, or null on the second item.

Usage

// private - for code of main (parent) class only
$result = $this->extract_directive_value( $directive_value, $default_namespace ): array;
$directive_value(string|true) (required)
The directive attribute value. It can be true when it's a boolean attribute.
$default_namespace(string|null)
The default namespace if none is explicitly defined.
Default: null

Changelog

Since 6.5.0 Introduced.

WP_Interactivity_API::extract_directive_value() code WP 6.6

private function extract_directive_value( $directive_value, $default_namespace = null ): array {
	if ( empty( $directive_value ) || is_bool( $directive_value ) ) {
		return array( $default_namespace, null );
	}

	// Replaces the value and namespace if there is a namespace in the value.
	if ( 1 === preg_match( '/^([\w\-_\/]+)::./', $directive_value ) ) {
		list($default_namespace, $directive_value) = explode( '::', $directive_value, 2 );
	}

	/*
	 * Tries to decode the value as a JSON object. If it fails and the value
	 * isn't `null`, it returns the value as it is. Otherwise, it returns the
	 * decoded JSON or null for the string `null`.
	 */
	$decoded_json = json_decode( $directive_value, true );
	if ( null !== $decoded_json || 'null' === $directive_value ) {
		$directive_value = $decoded_json;
	}

	return array( $default_namespace, $directive_value );
}