Skip to content

Commit

Permalink
PLAT-3484 update guzzle (#19)
Browse files Browse the repository at this point in the history
  • Loading branch information
Grzegorz Rajchman authored Apr 21, 2020
1 parent 574dbfc commit f9b7f10
Show file tree
Hide file tree
Showing 18 changed files with 967 additions and 1,536 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ changes.

Before releasing for general usage there will be major changes to the API. The library will move
away from the use of internal Talis project names like Persona, Critic, Babel and Echo etc.
Instead it will use more externally relavant names like ```ListReviews``` and ```Files```.
Instead it will use more externally relevant names like ```ListReviews``` and ```Files```.
The API will also move to a more domain driven design rather than the service driven design
of the individual libraries

Expand Down Expand Up @@ -44,7 +44,7 @@ Manually run persona locally:

# Create an OAuth Client and Secret

To build the talis-php docker container, you need to specify an oauth client and secret to use. This client should have `su` scope. It's not possibe to create a client with `su` scope via the API.
To build the talis-php docker container, you need to specify an oauth client and secret to use. This client should have `su` scope. It's not possible to create a client with `su` scope via the API.

First - create a client:

Expand Down Expand Up @@ -103,7 +103,7 @@ service redis-server start
source /etc/profile.d/*
```

You can the bun ant commands individually or run individual tests:
You can then run ant commands individually or run individual tests:

```bash
/vendor/bin/phpunit --filter testCreateUserThenPatchOAuthClientAddScope test/integration/
Expand Down
10 changes: 5 additions & 5 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "talis/talis-php",
"description": "This is a php client library for talis api's",
"version": "0.3.1",
"description": "This is a php client library for talis APIs",
"version": "0.5.0",
"keywords": [
"persona",
"echo",
Expand All @@ -15,13 +15,13 @@
"type": "library",
"license": "MIT",
"require": {
"php": ">=5.3.0",
"php": ">=5.5.9",
"monolog/monolog": ">=1.13.1",
"psr/log": ">=1.0.0",
"firebase/php-jwt": "^3.0",
"doctrine/common": "^2.5",
"predis/predis" : "v0.8.5",
"guzzle/guzzle": "^3.8"
"predis/predis" : ">=0.8.5",
"guzzlehttp/guzzle": "^6.0"
},
"require-dev": {
"phpunit/phpunit": "4.8.36",
Expand Down
89 changes: 41 additions & 48 deletions src/Talis/Babel/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

namespace Talis\Babel;

use Guzzle\Http\Message\Header;
use Guzzle\Http\Message\Header\HeaderCollection;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

Expand All @@ -27,7 +25,7 @@ class Client
private $babelPort;

/**
* @var \Guzzle\Http\Client
* @var \GuzzleHttp\Client
*/
private $httpClient = null;

Expand Down Expand Up @@ -124,8 +122,8 @@ public function getTargetFeedCount($target, $token, $deltaToken = 0)
$queryParams = http_build_query(['delta_token' => $deltaToken]);
$url = "/feeds/targets/$hash/activity/annotations?$queryParams";

$headers = $this->performBabelHead($url, $token);
$newItemsHeader = $headers->get('X-Feed-New-Items')->toArray();
$response = $this->performBabelHead($url, $token);
$newItemsHeader = $response->getHeader('X-Feed-New-Items');

if (count($newItemsHeader) !== 1) {
throw new \Talis\Babel\ClientException(
Expand Down Expand Up @@ -258,7 +256,7 @@ public function createAnnotation($token, array $arrData, $bCreateSynchronously =
if ($bCreateSynchronously) {
// Specific header that Babel server accepts to not return until the
// feed has also been created for the annotation.
$requestOptions = ['headers' => ['X-Ingest-Synchronously' => 'true']];
$requestOptions = [\GuzzleHttp\RequestOptions::HEADERS => ['X-Ingest-Synchronously' => 'true']];
}

$url = '/annotations';
Expand All @@ -283,13 +281,12 @@ protected function performBabelGet($url, $token)
];

$this->getLogger()->debug("Babel GET: $url", $headers);
$httpClient = $this->getHttpClient();

$request = $httpClient->get($url, $headers, ['exceptions' => false]);
$response = $request->send();

if ($response->isSuccessful()) {
$responseBody = $response->getBody(true);
try {
$response = $this->getHttpClient()->get($url, [
\GuzzleHttp\RequestOptions::HEADERS => $headers,
]);
$responseBody = (string) $response->getBody();
$arrResponse = json_decode($responseBody, true);

if ($arrResponse == null) {
Expand All @@ -299,14 +296,9 @@ protected function performBabelGet($url, $token)
}

return $arrResponse;
} catch (\GuzzleHttp\Exception\RequestException $exception) {
$this->handleBabelError($url, $exception);
}

/*
* For error scenarios we want to distinguish Persona problems and
* instances where no data is found. Anything else raises a generic
* \Talis\Babel\ClientException.
*/
$this->handleBabelError($url, $response);
}

/**
Expand All @@ -315,7 +307,7 @@ protected function performBabelGet($url, $token)
*
* @param string $url babel url
* @param string $token persona oauth token
* @return HeaderCollection
* @return \Psr\Http\Message\ResponseInterface
* @throws InvalidPersonaTokenException Invalid Persona oauth token
* @throws NotFoundException Babel feed not found
* @throws \Talis\Babel\ClientException Could not communicate with Babel
Expand All @@ -329,20 +321,15 @@ protected function performBabelHead($url, $token)

$this->getLogger()->debug('Babel HEAD: ' . $url, $headers);

$httpClient = $this->getHttpClient();
$request = $httpClient->head($url, $headers, ['exceptions' => false]);
$response = $request->send();
try {
$response = $this->getHttpClient()->head($url, [
\GuzzleHttp\RequestOptions::HEADERS => $headers,
]);

if ($response->isSuccessful()) {
return $response->getHeaders();
return $response;
} catch (\GuzzleHttp\Exception\RequestException $exception) {
$this->handleBabelError($url, $exception);
}

/*
* For error scenarios we want to distinguish Persona problems and
* instances where no data is found. Anything else raises a generic
* \Talis\Babel\ClientException.
*/
$this->handleBabelError($url, $response);
}

/**
Expand All @@ -367,18 +354,18 @@ protected function performBabelPost($url, $token, array $arrData, array $request
'Authorization' => "Bearer $token",
];

if (isset($requestOptions['headers'])) {
$headers = array_merge($headers, $requestOptions['headers']);
if (isset($requestOptions[\GuzzleHttp\RequestOptions::HEADERS])) {
$headers = array_merge($headers, $requestOptions[\GuzzleHttp\RequestOptions::HEADERS]);
}

$this->getLogger()->debug("Babel POST: $url", $arrData);

$httpClient = $this->getHttpClient();
$request = $httpClient->post($url, $headers, $arrData, ['exceptions' => false]);
$response = $request->send();

if ($response->isSuccessful()) {
$responseBody = $response->getBody(true);
try {
$response = $this->getHttpClient()->post($url, [
\GuzzleHttp\RequestOptions::HEADERS => $headers,
\GuzzleHttp\RequestOptions::FORM_PARAMS => $arrData,
]);
$responseBody = (string) $response->getBody();
$arrResponse = json_decode($responseBody, true);

if ($arrResponse == null) {
Expand All @@ -388,9 +375,9 @@ protected function performBabelPost($url, $token, array $arrData, array $request
}

return $arrResponse;
} catch (\GuzzleHttp\Exception\RequestException $exception) {
$this->handleBabelError($url, $exception);
}

$this->handleBabelError($url, $response);
}

/**
Expand Down Expand Up @@ -428,7 +415,7 @@ protected function getBabelPort()
/**
* Get an instance of the Guzzle HTTP client.
*
* @return \Guzzle\Http\Client
* @return \GuzzleHttp\Client
*/
protected function getHttpClient()
{
Expand All @@ -440,7 +427,7 @@ protected function getHttpClient()
$baseUrl .= ":$port";
}

$this->httpClient = new \Guzzle\Http\Client($baseUrl);
$this->httpClient = new \GuzzleHttp\Client(['base_uri' => $baseUrl]);
}

return $this->httpClient;
Expand All @@ -464,10 +451,16 @@ protected function checkKeysExist(array $keys, array $array)
/**
* Handle a babel error response
* @param string $url babel url which was called
* @param mixed $response http response
* @param \GuzzleHttp\Exception\RequestException $exception request exception
*/
protected function handleBabelError($url, $response)
protected function handleBabelError($url, \GuzzleHttp\Exception\RequestException $exception)
{
// Re-throw exception if it occurred before the response was produced
if (!$exception->hasResponse()) {
throw $exception;
}

$response = $exception->getResponse();
$statusCode = $response->getStatusCode();

switch ($statusCode) {
Expand All @@ -479,7 +472,7 @@ protected function handleBabelError($url, $response)
throw new NotFoundException("Nothing found for request: $url");
default:
$errorMessage = 'Unknown error';
$responseBody = $response->getBody(true);
$responseBody = (string) $response->getBody();

if ($responseBody) {
$arrResponse = json_decode($responseBody, true);
Expand All @@ -493,7 +486,7 @@ protected function handleBabelError($url, $response)
"Babel failed for request: $url",
[
'statusCode' => $statusCode,
'message' => $response->getMessage(),
'message' => $exception->getMessage(),
'body' => $responseBody,
]
);
Expand Down
30 changes: 15 additions & 15 deletions src/Talis/Critic/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class Client
protected $criticBaseUrl;

/**
* @var \Guzzle\Http\Client
* @var \GuzzleHttp\Client
*/
protected $httpClient;

Expand Down Expand Up @@ -72,12 +72,12 @@ public function setTokenClient(\Talis\Persona\Client\Tokens $personaClient)

/**
* For mocking
* @return \Guzzle\Http\Client
* @return \GuzzleHttp\Client
*/
protected function getHTTPClient()
{
if (!$this->httpClient) {
$this->httpClient = new \Guzzle\Http\Client();
$this->httpClient = new \GuzzleHttp\Client();
}

return $this->httpClient;
Expand All @@ -94,40 +94,40 @@ protected function getHTTPClient()
* for pre-existing access_token (and setting a new cookie
* with the resultant token)
* use_cache: (boolean) use cached called (defaults to true) </pre>
* @throws \Exception|\Guzzle\Http\Exception\ClientErrorResponseException Http communication error
* @throws \Exception|\GuzzleHttp\Exception\RequestException Http communication error
* @throws Exceptions\UnauthorisedAccessException Authorisation error
*/
public function createReview(array $postFields, $clientId, $clientSecret, array $headerParams = [])
{

try {
$client = $this->getHTTPClient();
$headers = $this->getHeaders($clientId, $clientSecret, $headerParams);

$request = $client->post($this->criticBaseUrl, $headers, $postFields);
$response = $request->send();
$response = $this->getHttpClient()->post($this->criticBaseUrl, [
\GuzzleHttp\RequestOptions::HEADERS => $headers,
\GuzzleHttp\RequestOptions::FORM_PARAMS => $postFields,
]);

if ($response->getStatusCode() == 201) {
$body = json_decode($response->getBody(true));
$responseBody = (string) $response->getBody();
$body = json_decode($responseBody);
return $body->id;
}

throw new \Talis\Critic\Exceptions\ReviewException();
} catch (\Guzzle\Http\Exception\ClientErrorResponseException $e) {
$response = $e->getResponse();
$error = $this->processErrorResponseBody($response->getBody(true));
} catch (\GuzzleHttp\Exception\RequestException $exception) {
$response = $exception->getResponse();
$error = $this->processErrorResponseBody((string) $response->getBody());

switch ($response->getStatusCode()) {
case 403:
case 401:
throw new \Talis\Critic\Exceptions\UnauthorisedAccessException(
$error['message'],
$error['error_code'],
$e
$exception
);
break;
default:
throw $e;
throw $exception;
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/Talis/EchoClient/Base.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,11 +77,11 @@ protected function getStringSizeInBytes($input)
/**
* To allow mocking of the Guzzle client for testing.
*
* @return Client
* @return \GuzzleHttp\Client
*/
protected function getHttpClient()
{
return new \Guzzle\Http\Client();
return new \GuzzleHttp\Client();
}

/**
Expand Down
Loading

0 comments on commit f9b7f10

Please sign in to comment.