Automattic\WooCommerce\Api\Infrastructure

GraphQLControllerBase::decode_json_paramprivateWC 1.0

Decode an optional JSON-object param (variables / extensions) into an array.

WP_REST_Request delivers POST-body params as already-decoded arrays, but GET query-string equivalents arrive as raw JSON strings. This helper unifies the two and rejects malformed JSON or non-object payloads with an InvalidArgumentException — which handle_request() surfaces as HTTP 400 INVALID_ARGUMENT, rather than letting a null decode slip through as "no variables" or a scalar decode trigger a downstream TypeError / HTTP 500.

Method of the class: GraphQLControllerBase{}

No Hooks.

Returns

Array. The decoded object, or an empty array when the param is omitted / empty / JSON null.

Usage

// private - for code of main (parent) class only
$result = $this->decode_json_param( $value, $name ): array;
$value(mixed) (required)
The param value from WP_REST_Request::get_param().
$name(string) (required)
The param name, used in error messages.

GraphQLControllerBase::decode_json_param() code WC 10.9.1

private function decode_json_param( $value, string $name ): array {
	if ( null === $value ) {
		return array();
	}
	if ( is_array( $value ) ) {
		return $value;
	}
	// phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Not HTML; serialized as JSON.
	if ( ! is_string( $value ) ) {
		throw new \InvalidArgumentException(
			sprintf( 'Argument `%s` must be a JSON object or omitted.', $name )
		);
	}
	if ( '' === $value ) {
		return array();
	}
	$decoded = json_decode( $value, true );
	if ( JSON_ERROR_NONE !== json_last_error() ) {
		throw new \InvalidArgumentException(
			sprintf( 'Argument `%s` is not valid JSON: %s', $name, json_last_error_msg() )
		);
	}
	if ( null === $decoded ) {
		// Literal "null" JSON payload — treat as omitted.
		return array();
	}
	if ( ! is_array( $decoded ) ) {
		throw new \InvalidArgumentException(
			sprintf( 'Argument `%s` must be a JSON object (got %s).', $name, gettype( $decoded ) )
		);
	}
	return $decoded;
	// phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped
}