Exemple #1
0
 /**
  * @param  Http\Response
  * @param  array|NULL  these codes are treated as success; code < 300 if NULL
  * @return mixed
  *
  * @throws ApiException
  */
 public function decode(Http\Response $response, array $okCodes = NULL)
 {
     $content = $response->getContent();
     if (preg_match('~application/json~i', $response->getHeader('Content-Type', ''))) {
         try {
             $content = Helpers::jsonDecode($response->getContent());
         } catch (JsonException $e) {
             throw new InvalidResponseException('JSON decoding failed.', 0, $e, $response);
         }
         if (!is_array($content) && !is_object($content)) {
             throw new InvalidResponseException('Decoded JSON is not an array or object.', 0, NULL, $response);
         }
     }
     $code = $response->getCode();
     if ($okCodes === NULL && $code >= 300 && $code != 304 || is_array($okCodes) && !in_array($code, $okCodes)) {
         /** @var $content \stdClass */
         switch ($code) {
             case Http\Response::S400_BAD_REQUEST:
                 throw new BadRequestException($content->message, $code, NULL, $response);
             case Http\Response::S401_UNAUTHORIZED:
                 throw new UnauthorizedException($content->message, $code, NULL, $response);
             case Http\Response::S403_FORBIDDEN:
                 if ($response->getHeader('X-RateLimit-Remaining') === '0') {
                     throw new RateLimitExceedException($content->message, $code, NULL, $response);
                 }
                 throw new ForbiddenException($content->message, $code, NULL, $response);
             case Http\Response::S404_NOT_FOUND:
                 throw new NotFoundException('Resource not found or not authorized to access.', $code, NULL, $response);
             case Http\Response::S422_UNPROCESSABLE_ENTITY:
                 $message = $content->message . implode(', ', array_map(function ($error) {
                     return '[' . implode(':', (array) $error) . ']';
                 }, $content->errors));
                 throw new UnprocessableEntityException($message, $code, NULL, $response);
         }
         $message = $okCodes === NULL ? '< 300' : implode(' or ', $okCodes);
         throw new UnexpectedResponseException("Expected response with code {$message}.", $code, NULL, $response);
     }
     return $content;
 }