1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
<?php
namespace Commercetools\Core\Client\Adapter;
use Commercetools\Core\Client\OAuth\TokenProvider;
use Commercetools\Core\Config;
use Commercetools\Core\Helper\CorrelationIdProvider;
use Commercetools\Core\Response\AbstractApiResponse;
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\TransferException;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\MessageFormatter;
use GuzzleHttp\Middleware;
use GuzzleHttp\Pool;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;
use Commercetools\Core\Error\ApiException;
use Psr\Log\LogLevel;
class Guzzle6Adapter implements AdapterOptionInterface, CorrelationIdAware, TokenProviderAware, ConfigAware
{
const DEFAULT_CONCURRENCY = 25;
protected $client;
protected $logger;
private $concurrency;
public function __construct(array $options = [])
{
$options = array_merge(
[
'allow_redirects' => false,
'verify' => true,
'timeout' => 60,
'connect_timeout' => 10,
'concurrency' => self::DEFAULT_CONCURRENCY
],
$options
);
$this->concurrency = $options['concurrency'];
$this->client = new Client($options);
}
public function setLogger(LoggerInterface $logger, $logLevel = LogLevel::INFO, $formatter = null)
{
if (is_null($formatter)) {
$formatter = new MessageFormatter();
}
$this->logger = $logger;
$this->addHandler(self::log($logger, $formatter, $logLevel), 'ctp_logger');
}
public function setCorrelationIdProvider(CorrelationIdProvider $provider)
{
$this->addHandler(Middleware::mapRequest(function (RequestInterface $request) use ($provider) {
return $request->withAddedHeader(
AbstractApiResponse::X_CORRELATION_ID,
$provider->getCorrelationId()
);
}), 'ctp_correlation_id');
}
public function setOAuthTokenProvider(TokenProvider $tokenProvider)
{
$this->addHandler(Middleware::mapRequest(function (RequestInterface $request) use ($tokenProvider) {
return $request->withAddedHeader(
'Authorization',
'Bearer ' . $tokenProvider->getToken()->getToken()
);
}), 'ctp_auth_provider');
}
private static function log(LoggerInterface $logger, MessageFormatter $formatter, $logLevel = LogLevel::INFO)
{
return function (callable $handler) use ($logger, $formatter, $logLevel) {
return function ($request, array $options) use ($handler, $logger, $formatter, $logLevel) {
return $handler($request, $options)->then(
function ($response) use ($logger, $request, $formatter, $logLevel) {
$message = $formatter->format($request, $response);
$context = [
AbstractApiResponse::X_CORRELATION_ID => $response->getHeader(
AbstractApiResponse::X_CORRELATION_ID
)
];
$logger->log($logLevel, $message, $context);
return $response;
},
function ($reason) use ($logger, $request, $formatter) {
$response = null;
$context = [];
if ($reason instanceof RequestException) {
$response = $reason->getResponse();
if (!is_null($response)) {
$context[AbstractApiResponse::X_CORRELATION_ID] = $response->getHeader(
AbstractApiResponse::X_CORRELATION_ID
);
}
}
$message = $formatter->format($request, $response, $reason);
$logger->notice($message, $context);
return \GuzzleHttp\Promise\rejection_for($reason);
}
);
};
};
}
public function addHandler($handler, $name = '')
{
$stack = $this->client->getConfig('handler');
$stack->push($handler, $name);
}
public function execute(RequestInterface $request, array $clientOptions = [])
{
try {
$response = $this->client->send($request, $clientOptions);
} catch (RequestException $exception) {
$response = $exception->getResponse();
throw ApiException::create($request, $response, $exception);
} catch (TransferException $exception) {
throw ApiException::create($request, null, $exception);
}
return $response;
}
public function executeBatch(array $requests, array $clientOptions = [])
{
$results = Pool::batch(
$this->client,
$requests,
[
'concurrency' => $this->concurrency,
'options' => $clientOptions
]
);
$responses = [];
foreach ($results as $key => $result) {
$httpResponse = $result;
if ($result instanceof RequestException) {
$request = $requests[$key];
$httpResponse = $result->getResponse();
$httpResponse = ApiException::create($request, $httpResponse, $result);
} elseif ($result instanceof TransferException) {
$request = $requests[$key];
$httpResponse = ApiException::create($request, null, $result);
}
$responses[$key] = $httpResponse;
}
return $responses;
}
public function authenticate($oauthUri, $clientId, $clientSecret, $formParams)
{
$options = [
'form_params' => $formParams,
'auth' => [$clientId, $clientSecret]
];
try {
$response = $this->client->post($oauthUri, $options);
} catch (RequestException $exception) {
throw ApiException::create($exception->getRequest(), $exception->getResponse(), $exception);
}
return $response;
}
public function executeAsync(RequestInterface $request, array $clientOptions = [])
{
$guzzlePromise = $this->client->sendAsync($request, $clientOptions);
return new Guzzle6Promise($guzzlePromise);
}
public static function getAdapterInfo()
{
if (defined('\GuzzleHttp\Client::MAJOR_VERSION')) {
$clientVersion = (string) constant(Client::class . '::MAJOR_VERSION');
} else {
$clientVersion = (string) constant(Client::class . '::VERSION');
}
return 'GuzzleHttp/' . $clientVersion;
}
public function getConfig($option)
{
return $this->client->getConfig($option);
}
}