public function decode(ResponseInterface $raw, $totalTime = 0) { $executionTime = $callTime = 0; if ($raw->hasHeader('X-Execution-Time')) { $executionTime = $raw->getHeader('X-Execution-Time'); } if ($raw->hasHeader('X-Call-Time')) { $callTime = $raw->getHeader('X-Call-Time'); } $body = ''; try { $body = (string) $raw->getBody(); $result = $this->_getDecoder()->decode($body, self::FORMAT, $this->_getDecodeContext()); } catch (\Exception $e) { if (!empty($body)) { $body = ' (' . $body . ')'; } error_log("Invalid API Response: " . $body); throw new InvalidApiResponseException("Unable to decode raw api response.", 500, $e); } if (!property_exists($result, 'type') || !property_exists($result, 'status') || !property_exists($result, 'result') || !property_exists($result->status, 'message') || !property_exists($result->status, 'code')) { error_log("Invalid API Result: " . json_encode($result)); throw new InvalidApiResponseException("Invalid api result", 500); } if ($executionTime === 0) { $executionTime = $totalTime; } if ($callTime === 0) { $callTime = $executionTime; } return ResponseBuilder::create(ApiCallData::create($result->type, $result->result, $result->status->code, $result->status->message, (double) str_replace([',', 'ms'], '', $totalTime), (double) str_replace([',', 'ms'], '', $executionTime), (double) str_replace([',', 'ms'], '', $callTime))); }
/** * @param ApiCallData $data * * @return ApiResponseInterface * * @throws \Exception */ public static function create(ApiCallData $data) { $type = $data->getResponseType(); if (!class_exists($type)) { throw new \Exception("Type Class '" . $type . "', could not be loaded"); } $interfaces = class_implements($type); if ($type == '\\Exception' || $type === '\\Packaged\\Api\\Exceptions\\ApiException' || in_array('\\Packaged\\Api\\Exceptions\\ApiException', $interfaces) || array_key_exists('Exception', class_parents($type))) { $code = $data->getStatusCode(); if (!is_numeric($code)) { $code = 500; } $exception = new $type($data->getStatusMessage(), $code); $rawData = $data->getRawResult(); if (is_object($rawData)) { Objects::hydrate($exception, $rawData); } throw $exception; } else { if (in_array('Packaged\\Api\\Interfaces\\ApiResponseInterface', $interfaces)) { $class = new $type(); /** * @var $class \Packaged\Api\Interfaces\ApiResponseInterface */ $class->setApiCallData($data); return $class; } else { throw new ApiException("An invalid message type was used '" . $type . "'"); } } }
/** * @param ApiCallData $callData * * @return ApiResponseInterface|static */ public function setApiCallData(ApiCallData $callData) { $this->_apiCallData = $callData; $data = $callData->getRawResult(); $this->hydrate($data); }