url = $url; } public static function request( string $url ): Http { return new self( $url ); } public function get( string $path = '' ): HttpResponse { return $this->make( $path, self::METHOD_GET ); } public function post( string $path = '' ): HttpResponse { return $this->make( $path, self::METHOD_POST ); } public function set_payload( array $data ): self { $this->payload = $data; return $this; } public function set_multipart_form_data( array $data ): self { $this->multipart_form_data = new MultipartFormData( $data ); return $this; } public function set_headers( array $headers ): self { $this->headers = array_merge( $this->headers, $headers ); return $this; } public function set_user_agent( string $user_agent ): self { $this->user_agent = $user_agent; return $this; } public function make( string $path = '', ?string $method = null ): HttpResponse { if ( empty( $this->url . $path ) ) { throw new EmptyUrlException( esc_html__( 'URL is empty', 'academy' ) ); } if ( $method && in_array( strtoupper( $method ), $this->allowed_http_verb, true ) ) { $this->method = strtoupper( $method ); } $args = [ 'redirection' => $this->redirection, 'method' => $this->method, 'timeout' => $this->timeout, 'blocking' => $this->blocking, 'httpversion' => $this->httpversion, ]; if ( ! empty( $this->user_agent ) ) { $args['user-agent'] = $this->user_agent; } if ( ! empty( $this->headers ) ) { $args['headers'] = $this->headers; } if ( ! empty( $this->cookies ) ) { $args['cookies'] = $this->cookies; } if ( ! empty( $this->payload ) ) { $args['body'] = trim( wp_json_encode( $this->payload ) ); } if ( ! is_null( $this->multipart_form_data ) ) { $args['body'] = $this->multipart_form_data->body; $args['headers'] = array_merge( $args['headers'] ?? [], $this->multipart_form_data->headers ); } $response = wp_remote_request( $this->url . $path, $args ); if ( is_wp_error( $response ) ) { throw new ReqFailedException( esc_html__( 'Request failed.', 'academy' ) ); } return new HttpResponse( $response ); } }