diff --git a/src/OneSignal.php b/src/OneSignal.php index e5a7529..36c3cf0 100644 --- a/src/OneSignal.php +++ b/src/OneSignal.php @@ -84,6 +84,35 @@ public function sendRequest(RequestInterface $request): array $content['_status_code'] = $response->getStatusCode(); } + return $content; + } + + public function makeRequest(RequestInterface $request): array + { + $response = $this->httpClient->sendRequest($request); + + $contentType = $response->getHeader('Content-Type')[0] ?? 'application/json'; + + if (!preg_match('/\bjson\b/i', $contentType)) { + throw new JsonException("Response content-type is '$contentType' while a JSON-compatible one was expected."); + } + + $content = $response->getBody()->__toString(); + + try { + $content = json_decode($content, true, 512, JSON_BIGINT_AS_STRING | JSON_THROW_ON_ERROR); + } catch (\JsonException $e) { + throw new JsonException($e->getMessage(), $e->getCode(), $e); + } + + if (!is_array($content)) { + throw new JsonException(sprintf('JSON content was expected to decode to an array, %s returned.', gettype($content))); + } + + if (!isset($content['_status_code'])) { + $content['_status_code'] = $response->getStatusCode(); + } + if ($content['_status_code'] >= 400) { throw new UnsuccessfulResponse($request, $response); } diff --git a/src/Segments.php b/src/Segments.php index 9f07337..69e1fb6 100644 --- a/src/Segments.php +++ b/src/Segments.php @@ -29,7 +29,7 @@ public function list(ListSegments $listSegmentsDto): ListSegmentsResponse $request = $this->createRequest('GET', '/apps/'.$appId.'/segments?'.http_build_query($listSegmentsDto->toArray())); $request = $request->withHeader('Authorization', "Basic {$this->client->getConfig()->getApplicationAuthKey()}"); - return ListSegmentsResponse::makeFromResponse($this->client->sendRequest($request)); + return ListSegmentsResponse::makeFromResponse($this->client->makeRequest($request)); } /** @@ -46,7 +46,7 @@ public function create(CreateSegment $createSegmentDto): CreateSegmentResponse $request = $request->withHeader('Content-Type', 'application/json'); $request = $request->withBody($this->createStream($createSegmentDto->toArray())); - return CreateSegmentResponse::makeFromResponse($this->client->sendRequest($request)); + return CreateSegmentResponse::makeFromResponse($this->client->makeRequest($request)); } /** @@ -63,6 +63,6 @@ public function delete(string $id): DeleteSegmentResponse $request = $this->createRequest('DELETE', '/apps/'.$appId.'/segments/'.$id); $request = $request->withHeader('Authorization', "Basic {$this->client->getConfig()->getApplicationAuthKey()}"); - return DeleteSegmentResponse::makeFromResponse($this->client->sendRequest($request)); + return DeleteSegmentResponse::makeFromResponse($this->client->makeRequest($request)); } }