WC_API_Server::dispatch()publicWC 2.1

Match the request to a callback and call it

Method of the class: WC_API_Server{}

Hooks from the method

Return

Mixed. The value returned by the callback, or a WP_Error instance

Usage

$WC_API_Server = new WC_API_Server();
$WC_API_Server->dispatch();

Changelog

Since 2.1 Introduced.

WC_API_Server::dispatch() code WC 8.7.0

public function dispatch() {

	switch ( $this->method ) {

		case 'HEAD' :
		case 'GET' :
			$method = self::METHOD_GET;
			break;

		case 'POST' :
			$method = self::METHOD_POST;
			break;

		case 'PUT' :
			$method = self::METHOD_PUT;
			break;

		case 'PATCH' :
			$method = self::METHOD_PATCH;
			break;

		case 'DELETE' :
			$method = self::METHOD_DELETE;
			break;

		default :
			return new WP_Error( 'woocommerce_api_unsupported_method', __( 'Unsupported request method', 'woocommerce' ), array( 'status' => 400 ) );
	}

	foreach ( $this->get_routes() as $route => $handlers ) {
		foreach ( $handlers as $handler ) {
			$callback  = $handler[0];
			$supported = isset( $handler[1] ) ? $handler[1] : self::METHOD_GET;

			if ( ! ( $supported & $method ) ) {
				continue;
			}

			$match = preg_match( '@^' . $route . '$@i', urldecode( $this->path ), $args );

			if ( ! $match ) {
				continue;
			}

			if ( ! is_callable( $callback ) ) {
				return new WP_Error( 'woocommerce_api_invalid_handler', __( 'The handler for the route is invalid', 'woocommerce' ), array( 'status' => 500 ) );
			}

			$args = array_merge( $args, $this->params['GET'] );
			if ( $method & self::METHOD_POST ) {
				$args = array_merge( $args, $this->params['POST'] );
			}
			if ( $supported & self::ACCEPT_DATA ) {
				$data = $this->handler->parse_body( $this->get_raw_data() );
				$args = array_merge( $args, array( 'data' => $data ) );
			} elseif ( $supported & self::ACCEPT_RAW_DATA ) {
				$data = $this->get_raw_data();
				$args = array_merge( $args, array( 'data' => $data ) );
			}

			$args['_method']  = $method;
			$args['_route']   = $route;
			$args['_path']    = $this->path;
			$args['_headers'] = $this->headers;
			$args['_files']   = $this->files;

			$args = apply_filters( 'woocommerce_api_dispatch_args', $args, $callback );

			// Allow plugins to halt the request via this filter
			if ( is_wp_error( $args ) ) {
				return $args;
			}

			$params = $this->sort_callback_params( $callback, $args );
			if ( is_wp_error( $params ) ) {
				return $params;
			}

			return call_user_func_array( $callback, $params );
		}
	}

	return new WP_Error( 'woocommerce_api_no_route', __( 'No route was found matching the URL and request method', 'woocommerce' ), array( 'status' => 404 ) );
}