Skip to content

Commit

Permalink
fix repeat request
Browse files Browse the repository at this point in the history
  • Loading branch information
Nadia committed May 17, 2018
1 parent 79c7cb1 commit 4fb47c5
Showing 1 changed file with 29 additions and 17 deletions.
46 changes: 29 additions & 17 deletions src/services/reports/ReportsService.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,9 @@ public function getReport(
return $this->getReportResponse($this->getRequesJson($reportDefinition), $mode, $returnMoneyInMicros);
}

public function getRequesJson(ReportDefinition $reportDefinition)
public function getRequesJson(ReportDefinition $reportDefinition)
{
$jsonRequest = ["params"=>$reportDefinition];
$jsonRequest = ["params" => $reportDefinition];
return json_encode($jsonRequest);
}

Expand Down Expand Up @@ -142,26 +142,19 @@ public function getReportResponse($payload, $mode, $returnMoneyInMicros)
$result = null;
while ($code !== 200) {
try {
$result = $this->service->doRequest($request);
//отправка повторного запросы при пустом ответе
if ($result === null) {
$result = $this->service->doRequest($request);
}
$result = $this->getResult(0, $request);
} catch (DirectApiException $ex) {
if ($ex->response) {

$simpleXMLElementResponse = new SimpleXMLElement($ex->response, 0, false, 'http://api.direct.yandex.com/v5/reports');
$errorCode = (int)$simpleXMLElementResponse->xpath('//reports:errorCode')[0];
if ($errorCode === 1002) {
$exResp = json_decode($ex->response, true);
$errorCode = (int)$exResp['error']['error_code'];
if ($errorCode === 500) {
try {
$result = $this->service->doRequest($request);
//отправка повторного запросы при пустом ответе
if ($result === null) {
$result = $this->service->doRequest($request);
}
$result = $this->getResult(0, $request);
} catch (BadResponseException $ex) {
$this->badResponseExceptionAnswer($ex);
}
} else {
$this->badResponseExceptionAnswer($ex);
}
}

Expand All @@ -186,9 +179,28 @@ public function getReportResponse($payload, $mode, $returnMoneyInMicros)
return $this->parseReportResponse($body);
}

/**
* @param $attemptNumber
* @param $request
* @return \Psr\Http\Message\ResponseInterface
* @throws DirectApiException
*/
private function getResult($attemptNumber, $request)
{
while ($attemptNumber < 100) {
$result = $this->service->doRequest($request);
if ($result === null) {
sleep(1);
$this->getResult($attemptNumber + 1, $request);
}
return $result;
}
throw new DirectApiException('Не удалось получить отчёт после 100 попыток');
}

private function parseApiError($errorString)
{
$errorJson= json_decode($errorString);
$errorJson = json_decode($errorString);
$requestId = (string)$errorJson->request_id;
$errorCode = (int)$errorJson->error_code;
$errorMessage = (string)$errorJson->error_string;
Expand Down

0 comments on commit 4fb47c5

Please sign in to comment.