diff --git a/src/Query/CurlQuery.php b/src/Query/CurlQuery.php index 16800c9..46d690c 100644 --- a/src/Query/CurlQuery.php +++ b/src/Query/CurlQuery.php @@ -44,6 +44,8 @@ class CurlQuery private $expectJSON_ignoreResContentType; /** @var bool */ private $debug; + /** @var string */ + private string $responseType; /** * CurlQuery constructor. @@ -85,19 +87,6 @@ public function auth(): Authentication return $this->auth; } - /** - * @return SSL - * @throws \Comely\Http\Exception\SSL_Exception - */ - public function ssl(): SSL - { - if (!$this->ssl) { - $this->ssl = new SSL(); - } - - return $this->ssl; - } - /** * @param int $version * @return CurlQuery @@ -112,6 +101,16 @@ public function useHttpVersion(int $version): self return $this; } + /** + * @param string|null $responseType + * @return $this + */ + public function forceResponseType(?string $responseType = null): self + { + $this->responseType = $responseType ?? "application/json; charset=utf-8"; + return $this; + } + /** * @param string|null $agent * @return CurlQuery @@ -271,16 +270,21 @@ public function send(): CurlResponse $responseIsJSON = is_string($responseType) && preg_match('/json/', $responseType) ? true : $this->expectJSON; if ($responseIsJSON) { if (!$this->expectJSON_ignoreResContentType) { + if ($this->responseType) { + $responseType = $this->responseType; + } if (!is_string($responseType)) { throw new HttpResponseException('Invalid "Content-type" header received, expecting JSON', $responseCode); } if (strtolower(trim(explode(";", $responseType)[0])) !== "application/json") { + throw new HttpResponseException( sprintf('Expected "application/json", got "%s"', $responseType), $responseCode ); } + } // Decode JSON body @@ -296,11 +300,24 @@ public function send(): CurlResponse throw new HttpResponseException('An error occurred while decoding JSON body'); } - if(is_array($json)) { + if (is_array($json)) { $response->payload()->use($json); } } return $response; } + + /** + * @return SSL + * @throws \Comely\Http\Exception\SSL_Exception + */ + public function ssl(): SSL + { + if (!$this->ssl) { + $this->ssl = new SSL(); + } + + return $this->ssl; + } }