WC_API_Server::sort_callback_params()protectedWC 2.2

Sort parameters by order specified in method declaration

Takes a callback and a list of available params, then filters and sorts by the parameters the method actually needs, using the Reflection API

Method of the class: WC_API_Server{}

No Hooks.

Return

Array|WP_Error.

Usage

// protected - for code of main (parent) or child class
$result = $this->sort_callback_params( $callback, $provided );
$callback(callable|array) (required)
the endpoint callback
$provided(array) (required)
the provided request parameters

Changelog

Since 2.2 Introduced.

WC_API_Server::sort_callback_params() code WC 8.9.0

protected function sort_callback_params( $callback, $provided ) {
	if ( is_array( $callback ) ) {
		$ref_func = new ReflectionMethod( $callback[0], $callback[1] );
	} else {
		$ref_func = new ReflectionFunction( $callback );
	}

	$wanted = $ref_func->getParameters();
	$ordered_parameters = array();

	foreach ( $wanted as $param ) {
		if ( isset( $provided[ $param->getName() ] ) ) {
			// We have this parameters in the list to choose from
			if ( 'data' == $param->getName() ) {
				$ordered_parameters[] = $provided[ $param->getName() ];
				continue;
			}

			$ordered_parameters[] = $this->urldecode_deep( $provided[ $param->getName() ] );
		} elseif ( $param->isDefaultValueAvailable() ) {
			// We don't have this parameter, but it's optional
			$ordered_parameters[] = $param->getDefaultValue();
		} else {
			// We don't have this parameter and it wasn't optional, abort!
			return new WP_Error( 'woocommerce_api_missing_callback_param', sprintf( __( 'Missing parameter %s', 'woocommerce' ), $param->getName() ), array( 'status' => 400 ) );
		}
	}

	return $ordered_parameters;
}