Skip to content

Commit

Permalink
Update SDK to latest version of API.
Browse files Browse the repository at this point in the history
  • Loading branch information
Simon Schurter committed Nov 1, 2017
1 parent 670a2ef commit 66c689c
Show file tree
Hide file tree
Showing 148 changed files with 10,221 additions and 3,134 deletions.
23 changes: 21 additions & 2 deletions lib/ApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,7 @@ public function selectHeaderContentType($content_type) {
* @return mixed
*/
public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType = null, $endpointPath = null) {
$request = new HttpRequest($this->getSerializer(), $this->buildRequestUrl($resourcePath, $queryParams), $method);
$request = new HttpRequest($this->getSerializer(), $this->buildRequestUrl($resourcePath, $queryParams), $method, $this->generateUniqueToken());
$request->setUserAgent($this->getUserAgent());
$request->addHeaders(array_merge(
(array)$this->defaultHeaders,
Expand All @@ -454,13 +454,18 @@ public function callApi($resourcePath, $method, $queryParams, $postData, $header
$data = $response->getBody();
}
} else {
if ($response->getStatusCode() == 409) {
throw new VersioningException();
}

$data = json_decode($response->getBody());
if (json_last_error() > 0) { // if response is a string
$data = $response->getBody();
}

throw new ApiException(
"[".$response->getStatusCode()."] Error connecting to the API (".$request->getUrl().")",
$request->getLogToken(),
'Error ' . $response->getStatusCode() . ' connecting to the API (' . $request->getUrl() . ')',
$response->getStatusCode(),
$response->getHeaders(),
$data
Expand Down Expand Up @@ -514,5 +519,19 @@ private function calculateHmac($securedData) {
$decodedSecret = base64_decode($this->applicationKey);
return base64_encode(hash_hmac("sha512", $securedData, $decodedSecret, true));
}

/**
* Generates a unique token to assign to the request.
*
* @return string
*/
private function generateUniqueToken() {
$s = strtoupper(md5(uniqid(rand(),true)));
return substr($s,0,8) . '-' .
substr($s,8,4) . '-' .
substr($s,12,4). '-' .
substr($s,16,4). '-' .
substr($s,20);
}

}
23 changes: 20 additions & 3 deletions lib/ApiException.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,16 @@ class ApiException extends Exception {
/**
* The deserialized response object.
*
* @var $responseObject
* @var mixed
*/
private $responseObject;

/**
* The log token.
*
* @var string
*/
private $logToken;

/**
* Constructor.
Expand All @@ -64,11 +71,12 @@ class ApiException extends Exception {
* @param mixed $responseBody the HTTP body of the server response either as Json or string
* @param mixed $responseObject the deseralized response object
*/
public function __construct($message = "", $code = 0, $responseHeaders = null, $responseBody = null, $responseObject = null) {
parent::__construct($message, $code);
public function __construct($logToken = null, $message = "", $code = 0, $responseHeaders = null, $responseBody = null, $responseObject = null) {
parent::__construct(($logToken != null ? '[' . $logToken . '] ' : '') . $message, $code);
$this->responseHeaders = $responseHeaders;
$this->responseBody = $responseBody;
$this->responseObject = $responseObject;
$this->logToken = $logToken;
}

/**
Expand Down Expand Up @@ -97,5 +105,14 @@ public function getResponseBody() {
public function getResponseObject() {
return $this->responseObject;
}

/**
* Return the log token.
*
* @return string
*/
public function getLogToken() {
return $this->logToken;
}

}
11 changes: 6 additions & 5 deletions lib/Http/CurlHttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public function send(ApiClient $apiClient, HttpRequest $request) {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($curl, CURLOPT_POSTFIELDS, $request->getBody());
} elseif ($request->getMethod() !== HttpRequest::GET) {
throw new ConnectionException($request->getUrl(), 'Method ' . $request->getMethod() . ' is not recognized.');
throw new ConnectionException($request->getUrl(), '[' . $request->getLogToken() . '] Method ' . $request->getMethod() . ' is not recognized.');
}
curl_setopt($curl, CURLOPT_URL, $request->getUrl());

Expand All @@ -100,7 +100,7 @@ public function send(ApiClient $apiClient, HttpRequest $request) {

// Make the request
$response = curl_exec($curl);
$response = $this->handleResponse($apiClient, $curl, $response, $request->getUrl());
$response = $this->handleResponse($apiClient, $request, $curl, $response, $request->getUrl());
curl_close($curl);
fclose($debugFilePointer);

Expand All @@ -111,12 +111,13 @@ public function send(ApiClient $apiClient, HttpRequest $request) {
* Puts together the HTTP response.
*
* @param ApiClient $apiClient the API client instance
* @param HttpRequest $request the HTTP request
* @param resource $curl the cURL handler
* @param mixed $response the response the of HTTP request
* @param string $url the url of the HTTP request
* @return HttpResponse
*/
private function handleResponse(ApiClient $apiClient, $curl, $response, $url) {
private function handleResponse(ApiClient $apiClient, HttpRequest $request, $curl, $response, $url) {
$http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$http_header = substr($response, 0, $http_header_size);
$http_body = substr($response, $http_header_size);
Expand All @@ -132,9 +133,9 @@ private function handleResponse(ApiClient $apiClient, $curl, $response, $url) {

// curl_exec can sometimes fail but still return a blank message from curl_error().
if (!empty($curl_error_message)) {
throw new ConnectionException($url, $curl_error_message);
throw new ConnectionException($url, '[' . $request->getLogToken() . '] ' . $curl_error_message);
} else {
throw new ConnectionException($url, 'API call failed for an unknown reason. This could happen if you are disconnected from the network.');
throw new ConnectionException($url, '[' . $request->getLogToken() . '] API call failed for an unknown reason. This could happen if you are disconnected from the network.');
}
} else {
return new HttpResponse($response_info['http_code'], $http_header, $http_body);
Expand Down
32 changes: 29 additions & 3 deletions lib/Http/HttpRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,13 @@ final class HttpRequest {
* @var string
*/
const HEADER_KEY_ACCEPT = 'accept';

/**
* The key of the 'x-wallee-logtoken' header.
*
* @var string
*/
const HEADER_LOG_TOKEN = 'x-wallee-logtoken';

/**
* The object serializer.
Expand Down Expand Up @@ -153,15 +160,23 @@ final class HttpRequest {
* @var string
*/
private $userAgent;

/**
* The log token.
*
* @var string
*/
private $logToken;

/**
* Constructor.
*
* @param ObjectSerializer $serializer the object serializer
* @param string $url the full qualified URL on which the request is executed
* @param string $method the request method (typically GET or POST)
* @param string $logToken the request's log token
*/
public function __construct(ObjectSerializer $serializer, $url, $method) {
public function __construct(ObjectSerializer $serializer, $url, $method, $logToken) {
$this->serializer = $serializer;
$this->url = $url;
$this->method = strtoupper($method);
Expand All @@ -170,8 +185,10 @@ public function __construct(ObjectSerializer $serializer, $url, $method) {
$this->host = parse_url($url, PHP_URL_HOST);
$this->port = parse_url($url, PHP_URL_PORT);
$this->query = parse_url($url, PHP_URL_QUERY);
$this->logToken = $logToken;

$this->addHeader(self::HEADER_KEY_HOST, $this->host);
$this->addHeader(self::HEADER_LOG_TOKEN, $this->logToken);
}

/**
Expand Down Expand Up @@ -309,6 +326,15 @@ public function setUserAgent($userAgent) {
$this->addHeader(self::HEADER_KEY_USER_AGENT, $userAgent);
return $this;
}

/**
* Returns the log token.
*
* @return string
*/
public function getLogToken() {
return $this->logToken;
}

/**
* Returns the query part of the request as string.
Expand All @@ -331,8 +357,8 @@ public function getBody() {
(!isset($this->headers[self::HEADER_KEY_CONTENT_TYPE]) || $this->headers[self::HEADER_KEY_CONTENT_TYPE] != 'multipart/form-data')) {
return json_encode($this->serializer->sanitizeForSerialization($this->body));
} else {
return $this->body;
}
return $this->body;
}
}

/**
Expand Down
31 changes: 17 additions & 14 deletions lib/Http/SocketHttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public function isSupported() {
public function send(ApiClient $apiClient, HttpRequest $request) {
$this->resetStartTime();
$socket = $this->startStreamSocket($apiClient, $request);
$responseMessage = $this->readFromSocket($apiClient, $socket);
$responseMessage = $this->readFromSocket($apiClient, $request, $socket);
fclose($socket);

// debug HTTP response
Expand All @@ -58,7 +58,7 @@ public function send(ApiClient $apiClient, HttpRequest $request) {

if (empty($responseMessage)) {
throw new ConnectionException($request->getUrl(),
"The server responded with an empty response (no HTTP header and no HTTP body).");
'[' . $request->getLogToken() . '] The server responded with an empty response (no HTTP header and no HTTP body).');
}

return new HttpResponse($responseMessage);
Expand All @@ -71,11 +71,12 @@ public function send(ApiClient $apiClient, HttpRequest $request) {
* chunks, the connection can be closed earlier after the last chunk.
*
* @param ApiClient $apiClient the API client instance
* @param HttpRequest $request the HTTP request
* @param resource $socket the socket
* @throws ConnectionException
* @return string
*/
private function readFromSocket($apiClient, $socket) {
private function readFromSocket(ApiClient $apiClient, HttpRequest $request, $socket) {
$inBody = false;
$responseMessage = '';
$chunked = false;
Expand All @@ -85,7 +86,7 @@ private function readFromSocket($apiClient, $socket) {
$endReached = false;
while ($maxTime > time() && !feof($socket) && !$endReached) {
if ($inBody === false) {
$line = $this->readLineFromSocket($apiClient, $socket, 2048);
$line = $this->readLineFromSocket($apiClient, $request, $socket, 2048);
if ($line == "\r\n") {
$inBody = true;
}
Expand All @@ -111,7 +112,7 @@ private function readFromSocket($apiClient, $socket) {
if ($contentLength > 0) {
$readBytes = $contentLength;
}
$tmp = $this->readContentFromSocket($apiClient, $socket, $readBytes);
$tmp = $this->readContentFromSocket($apiClient, $request, $socket, $readBytes);
$responseMessage .= $tmp;
if (strlen($tmp) == $readBytes) {
$endReached = true;
Expand All @@ -130,7 +131,7 @@ private function readFromSocket($apiClient, $socket) {

// We have to read the chunk, when it is greater than zero. The last one is always 0.
else if ($chunkLength > 0) {
$responseMessage .= $this->readContentFromSocket($apiClient, $socket, $chunkLength);
$responseMessage .= $this->readContentFromSocket($apiClient, $request, $socket, $chunkLength);

// We skip the next line break.
fseek($socket, 2, SEEK_CUR);
Expand All @@ -151,7 +152,7 @@ private function readFromSocket($apiClient, $socket) {
}
else {
throw new ConnectionException(null,
"The remote server did not respond within '" . $apiClient->getConnectionTimeout() . "' seconds.");
'[' . $request->getLogToken() . '] The remote server did not respond within ' . $apiClient->getConnectionTimeout() . ' seconds.');
}
}

Expand All @@ -161,12 +162,13 @@ private function readFromSocket($apiClient, $socket) {
* We need this method because neither fread nor stream_get_contents do respect timeouts.
*
* @param ApiClient $apiClient the API client instance
* @param HttpRequest $request the HTTP request
* @param resource $socket the socket from which should be read
* @param int $maxNumberOfBytes the number of bytes to read
* @throws ConnectionException
* @return string
*/
private function readContentFromSocket($apiClient, $socket, $maxNumberOfBytes) {
private function readContentFromSocket(ApiClient $apiClient, HttpRequest $request, $socket, $maxNumberOfBytes) {
stream_set_blocking($socket, false);
$maxTime = $this->getStartTime() + $apiClient->getConnectionTimeout();
$numberOfBytesRead = 0;
Expand All @@ -190,7 +192,7 @@ private function readContentFromSocket($apiClient, $socket, $maxNumberOfBytes) {
}
else {
throw new ConnectionException(null,
"The remote server did not respond within '" . $apiClient->getConnectionTimeout() . "' seconds.");
'[' . $request->getLogToken() . '] The remote server did not respond within ' . $apiClient->getConnectionTimeout() . ' seconds.');
}
}

Expand All @@ -199,12 +201,13 @@ private function readContentFromSocket($apiClient, $socket, $maxNumberOfBytes) {
* configured.
*
* @param ApiClient $apiClient the API client instance
* @param HttpRequest $request the HTTP request
* @param resource $socket the socket from which should be read
* @param int $maxNumberOfBytes the number of bytes to read
* @throws ConnectionException
* @return string
*/
private function readLineFromSocket($apiClient, $socket, $maxNumberOfBytes) {
private function readLineFromSocket(ApiClient $apiClient, HttpRequest $request, $socket, $maxNumberOfBytes) {
stream_set_blocking($socket, false);
$maxTime = $this->getStartTime() + $apiClient->getConnectionTimeout();
$result = false;
Expand All @@ -225,7 +228,7 @@ private function readLineFromSocket($apiClient, $socket, $maxNumberOfBytes) {
}
else {
throw new ConnectionException(null,
"The remote server did not respond within '" . $apiClient->getConnectionTimeout() . "' seconds.");
'[' . $request->getLogToken() . '] The remote server did not respond within ' . $apiClient->getConnectionTimeout() . ' seconds.');
}
}

Expand All @@ -250,7 +253,7 @@ private function startStreamSocket(ApiClient $apiClient, HttpRequest $request) {

$result = fwrite($socket, $message);
if ($result == false) {
throw new ConnectionException($request->getUrl(), 'Could not send the message to the server.');
throw new ConnectionException($request->getUrl(), '[' . $request->getLogToken() . '] Could not send the message to the server.');
}
return $socket;
}
Expand Down Expand Up @@ -307,12 +310,12 @@ private function createSocketStream(ApiClient $apiClient, HttpRequest $request)
$this->createStreamContext($apiClient, $request));

if ($filePointer === false) {
throw new ConnectionException($request->getUrl(), $errstr);
throw new ConnectionException($request->getUrl(), '[' . $request->getLogToken() . '] ' . $errstr);
}

if (!(get_resource_type($filePointer) == 'stream')) {
$errorMessage = 'Could not connect to the server. The returned socket was not a stream.';
throw new ConnectionException($request->getUrl(), $errorMessage);
throw new ConnectionException($request->getUrl(), '[' . $request->getLogToken() . '] ' . $errorMessage);
}

return $filePointer;
Expand Down
Loading

0 comments on commit 66c689c

Please sign in to comment.