Yoast\WP\SEO\AI_HTTP_Request\Infrastructure

API_Client::perform_requestpublicYoast 1.0

Performs a request to the API.

Метод класса: API_Client{}

Хуки из метода

Возвращает

Массив>. The response from the API.

Использование

$API_Client = new API_Client();
$API_Client->perform_request( $action_path, $body, $headers, $http_method ): array;
$action_path(строка) (обязательный)
The action path for the request.
$body(array|null) (обязательный)
The body of the request, or null/empty to send no body.
$headers(array) (обязательный)
The headers for the request.
$http_method(строка) (обязательный)
The HTTP method for the request. One of Request::METHOD_*.

Код API_Client::perform_request() Yoast 28.2

public function perform_request( string $action_path, $body, $headers, string $http_method ): array {
	// Our API expects JSON.
	$headers   = \array_merge( $headers, [ 'Content-Type' => 'application/json' ] );
	$arguments = [
		'timeout' => $this->get_request_timeout(),
		'headers' => $headers,
	];

	// Only POST sends a body to the AI API today; GET and DELETE endpoints do not. An empty body is
	// omitted entirely: an empty array is ambiguous once JSON-encoded (`[]` vs `{}`) and the AI
	// service rejects it, so a bodyless POST is sent instead.
	if ( $http_method === Request::METHOD_POST && ! empty( $body ) ) {
		// phpcs:ignore Yoast.Yoast.JsonEncodeAlternative.Found -- Reason: We don't want the debug/pretty possibility.
		$arguments['body'] = WPSEO_Utils::format_json_encode( $body );
	}

	/**
	 * Filter: 'Yoast\WP\SEO\ai_api_url' - Replaces the default URL for the AI API with a custom one.
	 *
	 * @internal
	 *
	 * @param string $url The default URL for the AI API.
	 */
	$url = \apply_filters( 'Yoast\WP\SEO\ai_api_url', $this->base_url );

	switch ( $http_method ) {
		case Request::METHOD_POST:
			$response = \wp_remote_post( $url . $action_path, $arguments );
			break;
		case Request::METHOD_GET:
			$response = \wp_remote_get( $url . $action_path, $arguments );
			break;
		case Request::METHOD_DELETE:
			$response = \wp_remote_request( $url . $action_path, \array_merge( $arguments, [ 'method' => 'DELETE' ] ) );
			break;
		default:
			// Defensive: the Request constructor already validates the method, so we should never reach this branch.
			// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- false positive.
			throw new WP_Request_Exception( "Unsupported HTTP method: $http_method" );
	}

	if ( \is_wp_error( $response ) ) {
		// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- false positive.
		throw new WP_Request_Exception( $response->get_error_message() );
	}

	return $response;
}