timeout = $timeout; } /** * @param array $headers * @param array $queryParams */ public function get( string $url, array $headers = [], array $queryParams = [] ): HttpResponse { if ( ! empty( $queryParams ) ) { $url = add_query_arg( $queryParams, $url ); } $response = wp_safe_remote_get( $url, [ 'timeout' => $this->timeout, 'headers' => $headers, 'sslverify' => true, ] ); return $this->parse( $response ); } /** * @param array $headers * @param array $body */ public function post( string $url, array $headers = [], array $body = [] ): HttpResponse { // JSON-encode the body when the caller declares application/json. // wp_remote_post() would otherwise form-encode an array regardless of Content-Type. $lowerHeaders = array_change_key_case( $headers, CASE_LOWER ); $contentType = isset( $lowerHeaders['content-type'] ) ? (string) $lowerHeaders['content-type'] : ''; $requestBody = ( false !== stripos( $contentType, 'application/json' ) ) ? (string) wp_json_encode( $body ) : $body; $response = wp_safe_remote_post( $url, [ 'timeout' => $this->timeout, 'headers' => $headers, 'body' => $requestBody, 'sslverify' => true, ] ); return $this->parse( $response ); } /** * @param array|\WP_Error $response * @throws \RuntimeException On network error. */ private function parse( $response ): HttpResponse { if ( is_wp_error( $response ) ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- exception messages are not HTML output. throw new \RuntimeException( $response->get_error_message() ); } $headers_obj = wp_remote_retrieve_headers( $response ); // A dictionary object from Requests, or a plain array when a // pre_http_request filter / custom transport supplies the response. $headers = $headers_obj instanceof \WpOrg\Requests\Utility\CaseInsensitiveDictionary ? $headers_obj->getAll() : $headers_obj; return new HttpResponse( (int) wp_remote_retrieve_response_code( $response ), (string) wp_remote_retrieve_body( $response ), $headers ); } }