Esempio n. 1
0
 public function parseResponse($url, $response, $returnType, $isArray, $expectedHttpCodes, $errorHttpCodes)
 {
     // parse response
     $header = false;
     $content = array();
     $status = null;
     foreach (explode("\r\n", $response) as $line) {
         if (strpos($line, 'HTTP/1.1') === 0) {
             $lineParts = explode(' ', $line);
             $status = intval($lineParts[1]);
             $header = true;
         } else {
             if ($line == '') {
                 $header = false;
             } else {
                 if ($header) {
                     $line = explode(': ', $line);
                     switch ($line[0]) {
                         case 'Status':
                             $status = intval(substr($line[1], 0, 3));
                             break;
                     }
                 } else {
                     $content[] = $line;
                 }
             }
         }
     }
     if (is_null($status)) {
         throw new ActivitiClientException("No valid response accepted, URL [{$url}]", ActivitiClientException::NO_VALID_RESPONSE);
     }
     if (in_array($status, $expectedHttpCodes)) {
         $response = implode("\r\n", $content);
         if (!trim($response)) {
             return;
         }
         if ($returnType == 'string') {
             return $response;
         }
         $response = json_decode($response);
         if ($returnType) {
             if ($isArray) {
                 return ActivitiResponseObject::fromArray($response, $returnType);
             }
             return new $returnType($response);
         }
         return;
     }
     if ($response && json_decode(implode("\n", $content))) {
         $error = json_decode(implode("\n", $content));
         if (isset($error->statusCode) && isset($error->errorMessage)) {
             throw new ActivitiClientException("Status [{$error->statusCode}], URL [{$url}]: {$error->errorMessage}", ActivitiClientException::INVALID_HTTP_CODE);
         }
     }
     if (isset($errorHttpCodes[$status])) {
         throw new ActivitiClientException("Status [{$status}], URL [{$url}]: " . $errorHttpCodes[$status], ActivitiClientException::INVALID_HTTP_CODE);
     }
     if (ActivitiResponseType::isExpectedCode($status)) {
         throw new ActivitiClientException("Status [{$status}], URL [{$url}]: " . ActivitiResponseType::getCodeDescription($status), ActivitiClientException::INVALID_HTTP_CODE);
     }
     throw new ActivitiClientException("Unexpected status [{$status}], URL [{$url}]", ActivitiClientException::INVALID_HTTP_CODE);
 }