load()->getConfig(); $this->setConfig($config); $apiClient->setConfig($config); $this->attempts = self::DEFAULT_ATTEMPTS_COUNT; $this->apiClient = $apiClient; } /** * @param $login * @param $password * * @return static $this */ public function setAuth($login, $password) { $this->login = $login; $this->password = $password; $this->apiClient ->setBearerToken(null) ->setShopId($this->login) ->setShopPassword($this->password); return $this; } /** * @param $token * * @return $this */ public function setAuthToken($token) { $this->apiClient ->setShopId(null) ->setShopPassword(null) ->setBearerToken($token); return $this; } /** * @return ApiClientInterface */ public function getApiClient() { return $this->apiClient; } /** * @param ApiClientInterface $apiClient * * @return static $this */ public function setApiClient(ApiClientInterface $apiClient) { $this->apiClient = $apiClient; $this->apiClient->setConfig($this->config); $this->apiClient->setLogger($this->logger); return $this; } /** * Устанавливает логгер приложения * * @param null|callable|object|LoggerInterface $value Инстанс логгера */ public function setLogger($value) { if ($value === null || $value instanceof LoggerInterface) { $this->logger = $value; } else { $this->logger = new LoggerWrapper($value); } if ($this->apiClient !== null) { $this->apiClient->setLogger($this->logger); } } /** * @return array */ public function getConfig() { return $this->config; } /** * @param array $config */ public function setConfig($config) { $this->config = $config; } /** * Установка значение задержки между повторными запросами * * @param int $timeout * * @return static */ public function setRetryTimeout($timeout) { $this->timeout = $timeout; return $this; } /** * Установка значения количества попыток повторных запросов при статусе 202 * * @param int $attempts * * @return static */ public function setMaxRequestAttempts($attempts) { $this->attempts = $attempts; return $this; } /** * @param $serializedData * * @return string * @throws Exception */ protected function encodeData($serializedData) { if ($serializedData === array()) { return '{}'; } if (defined('JSON_UNESCAPED_UNICODE') && defined('JSON_UNESCAPED_SLASHES')) { $encoded = json_encode($serializedData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); } else { $encoded = self::_unescaped(json_encode($serializedData)); } if ($encoded === false) { $errorCode = json_last_error(); throw new JsonException("Failed serialize json.", $errorCode); } return $encoded; } /** * @param string $json * @return string|false */ private static function _unescaped($json) { if ($json === false) { return false; } $json = str_replace('\\/', '/', $json); return preg_replace_callback('/\\\\u(\w{4})/', function ($matches) { return html_entity_decode('&#x' . $matches[1] . ';', ENT_COMPAT, 'UTF-8'); }, $json); } /** * @param ResponseObject $response * * @return array */ protected function decodeData(ResponseObject $response) { $resultArray = json_decode($response->getBody(), true); if ($resultArray === null) { throw new JsonException('Failed to decode response', json_last_error()); } return $resultArray; } /** * @param ResponseObject $response * * @throws ApiException * @throws BadApiRequestException * @throws ForbiddenException * @throws InternalServerError * @throws NotFoundException * @throws ResponseProcessingException * @throws TooManyRequestsException * @throws UnauthorizedException */ protected function handleError(ResponseObject $response) { switch ($response->getCode()) { case BadApiRequestException::HTTP_CODE: throw new BadApiRequestException($response->getHeaders(), $response->getBody()); break; case ForbiddenException::HTTP_CODE: throw new ForbiddenException($response->getHeaders(), $response->getBody()); break; case UnauthorizedException::HTTP_CODE: throw new UnauthorizedException($response->getHeaders(), $response->getBody()); break; case InternalServerError::HTTP_CODE: throw new InternalServerError($response->getHeaders(), $response->getBody()); break; case NotFoundException::HTTP_CODE: throw new NotFoundException($response->getHeaders(), $response->getBody()); break; case TooManyRequestsException::HTTP_CODE: throw new TooManyRequestsException($response->getHeaders(), $response->getBody()); break; case ResponseProcessingException::HTTP_CODE: throw new ResponseProcessingException($response->getHeaders(), $response->getBody()); break; default: if ($response->getCode() > 399) { throw new ApiException( 'Unexpected response error code', $response->getCode(), $response->getHeaders(), $response->getBody() ); } } } /** * Задержка между повторными запросами * * @param $response */ protected function delay($response) { $timeout = $this->timeout; $responseData = $this->decodeData($response); if ($timeout) { $delay = $timeout; } else { if (isset($responseData['retry_after'])) { $delay = $responseData['retry_after']; } else { $delay = self::DEFAULT_DELAY; } } usleep($delay * 1000); } /** * Выполнение запроса и обработка 202 статуса * * @param $path * @param $method * @param $queryParams * @param null $httpBody * @param array $headers * * @return mixed|ResponseObject * @throws ApiException * @throws AuthorizeException * @throws ApiConnectionException * @throws ExtensionNotFoundException */ protected function execute($path, $method, $queryParams, $httpBody = null, $headers = array()) { $attempts = $this->attempts; $response = $this->apiClient->call($path, $method, $queryParams, $httpBody, $headers); while (in_array($response->getCode(), array(202, 500)) && $attempts > 0) { $this->delay($response); $attempts--; $response = $this->apiClient->call($path, $method, $queryParams, $httpBody, $headers); } return $response; } }