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 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
<?php
namespace Commercetools\Core\Client;
use Commercetools\Core\Cache\CacheAdapterFactory;
use Commercetools\Core\Client\OAuth\CacheTokenProvider;
use Commercetools\Core\Client\OAuth\ClientCredentials;
use Commercetools\Core\Client\OAuth\CredentialTokenProvider;
use Commercetools\Core\Client\OAuth\OAuth2Handler;
use Commercetools\Core\Client\OAuth\TokenProvider;
use Commercetools\Core\Config;
use Commercetools\Core\Error\ApiException;
use Commercetools\Core\Error\DeprecatedException;
use Commercetools\Core\Error\InvalidTokenException;
use Commercetools\Core\Error\Message;
use Commercetools\Core\Helper\CorrelationIdProvider;
use Commercetools\Core\Error\InvalidArgumentException;
use Commercetools\Core\Model\Common\Context;
use Commercetools\Core\Model\Common\ContextAwareInterface;
use Commercetools\Core\Response\AbstractApiResponse;
use GuzzleHttp\Client;
use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\MessageFormatter;
use GuzzleHttp\Middleware;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Psr\SimpleCache\CacheInterface;
/**
* The factory to create a Client for communicating with Composable Commerce
*
* @description
* This factory will create a Guzzle HTTP Client preconfigured for talking to Composable Commerce
*
* ## Instantiation
*
* ```php
* $config = Config::fromArray(
* ['client_id' => '<client_id>', 'client_secret' => '<client_secret>', 'project' => '<project>']
* );
* $client = ClientFactory::of()->createClient($config);
* ```
*
* ## Execution
*
* ### Synchronous
*
* ```php
* $request = ProductProjectionSearchRequest::of();
* $response = $client->execute($request);
* $products = $request->mapFromResponse($response);
* ```
*
* ### Asynchronous
* The asynchronous execution will return a promise to fulfill the request.
*
* ```php
* $request = ProductProjectionSearchRequest::of();
* $response = $client->executeAsync($request);
* $products = $request->mapFromResponse($response->wait());
* ```
*
* ### Batch
* By filling the batch queue and starting the execution all requests will be executed in parallel.
*
* ```php
* $responses = Pool::batch(
* $client,
* [ProductProjectionSearchRequest::of()->httpRequest(), CartByIdGetRequest::ofId($cartId)->httpRequest()]
* );
* ```
*
* ## Instantiation options
*
* ### Using a logger
*
* The client uses the PSR-3 logger interface for logging requests and deprecation notices. To enable
* logging provide a PSR-3 compliant logger (e.g. Monolog).
*
* ```php
* $logger = new \Monolog\Logger('name');
* $logger->pushHandler(new StreamHandler('./requests.log'));
* $client = ClientFactory::of()->createClient($config, $logger);
* ```
*
* ### Using a cache adapter ###
*
* The client will automatically request an OAuth token and store the token in the provided cache.
*
* It's also possible to use a different cache adapter. The SDK provides a Doctrine, a Redis and an APCu cache adapter.
* By default the SDK tries to instantiate the APCu or a PSR-6 filesystem cache adapter if there is no cache given.
* E.g. Redis:
*
* ```php
* $redis = new \Redis();
* $redis->connect('localhost');
* $client = ClientFactory::of()->createClient($config, null, $cache);
* ```
*
* #### Using cache and logger ####
*
* ```php
* $client = ClientFactory::of()->createClient($config, $logger, $cache);
* ```
*
* #### Using a custom cache adapter ####
*
* ```php
* class <CacheClass>Adapter implements \Psr\Cache\CacheItemPoolInterface {
* protected $cache;
* public function __construct(<CacheClass> $cache) {
* $this->cache = $cache;
* }
* }
*
* $client->getAdapterFactory()->registerCallback(function ($cache) {
* if ($cache instanceof <CacheClass>) {
* return new <CacheClass>Adapter($cache);
* }
* return null;
* });
* ```
*
* ### Using a custom client class
*
* If some additional configuration is needed or the client should have custom logic you could provide a class name
* to be used for the client instance. This class has to be an extended Guzzle client.
*
* ```php
* $client = ClientFactory::of()->createCustomClient(MyCustomClient::class, $config);
* ```
*
* ## Middlewares
*
* Adding middlewares to the clients for Composable Commerce as well for the authentication can be done using the config
* by setting client options.
*
* ### Using a HandlerStack
*
* ```php
* $handler = HandlerStack::create();
* $handler->push(Middleware::mapRequest(function (RequestInterface $request) {
* ...
* return $request; })
* );
* $config = Config::of()->setClientOptions(['handler' => $handler])
* ```
*
* ### Using a middleware array
*
* ```php
* $middlewares = [
* Middleware::mapRequest(function (RequestInterface $request) {
* ...
* return $request; }),
* ...
* ]
* $config = Config::of()->setClientOptions(['middlewares' => $middlewares])
* ```
*
* ### Timeouts
*
* The clients are configured to timeout by default after 60 seconds. This can be changed by setting the client options in the Config instance
*
* ```php
* $config = Config::of()->setClientOptions([
* 'defaults' => [
* 'timeout' => 10
* ]
* ])
* ```
*
* Another option is to specify the timeout per request
*
* ```php
* $request = ProductProjectionSearchRequest::of();
* $response = $client->execute($request, null, ['timeout' => 10]);
* ```
*
* ### Retrying
*
* As a request can error in multiple ways it's possible to add a retry middleware to the client config. E.g.: Retrying in case of service unavailable errors
*
* ```php
* $config = Config::of()->setClientOptions([
* 'defaults' => [
* 'timeout' => 10
* ]
* ])
* $maxRetries = 3;
* $clientOptions = [
* 'middlewares' => [
* 'retry' => Middleware::retry(
* function ($retries, RequestInterface $request, ResponseInterface $response = null, $error = null) use ($maxRetries) {
* if ($response instanceof ResponseInterface && $response->getStatusCode() < 500) {
* return false;
* }
* if ($retries > $maxRetries) {
* return false;
* }
* if ($error instanceof ServiceUnavailableException) {
* return true;
* }
* if ($error instanceof ServerException && $error->getCode() == 503) {
* return true;
* }
* if ($response instanceof ResponseInterface && $response->getStatusCode() == 503) {
* return true;
* }
* return false;
* },
* [RetryMiddleware::class, 'exponentialDelay']
* )
* ]
* ];
* $config->setClientOptions($clientOptions);
* ```
* @package Commercetools\Core\Client
*/
class ClientFactory
{
/**
* @var bool
*/
private static $isGuzzle6;
/**
* ClientFactory constructor.
* @throws DeprecatedException
*/
public function __construct()
{
if (!self::isGuzzle6()) {
throw new DeprecatedException("ClientFactory doesn't support Guzzle version < 6");
}
}
/**
* @param string $clientClass
* @param Config|array $config
* @param LoggerInterface $logger
* @param CacheItemPoolInterface|CacheInterface $cache
* @param TokenProvider $provider
* @param CacheAdapterFactory $cacheAdapterFactory
* @param Context|null $context
* @return Client
*/
public function createCustomClient(
$clientClass,
$config,
LoggerInterface $logger = null,
$cache = null,
TokenProvider $provider = null,
CacheAdapterFactory $cacheAdapterFactory = null,
Context $context = null
) {
$config = $this->createConfig($config);
if (is_null($context)) {
$context = $config->getContext();
}
if (is_null($cacheAdapterFactory)) {
$cacheDir = $config->getCacheDir();
$cacheDir = !is_null($cacheDir) ? $cacheDir : realpath(__DIR__ . '/../../..');
$cacheAdapterFactory = new CacheAdapterFactory($cacheDir);
}
$cache = $cacheAdapterFactory->get($cache);
if (is_null($cache)) {
throw new InvalidArgumentException(Message::INVALID_CACHE_ADAPTER);
}
$credentials = $config->getClientCredentials();
$oauthHandler = $this->getHandler(
$credentials,
$config->getOauthUrl(),
$cache,
$provider,
$config->getOAuthClientOptions(),
$config->getCorrelationIdProvider()
);
$options = $this->getDefaultOptions($config);
$client = $this->createGuzzle6Client(
$clientClass,
$options,
$oauthHandler,
$logger,
$config->getCorrelationIdProvider()
);
if ($client instanceof ContextAwareInterface) {
$client->setContext($context);
}
return $client;
}
/**
* @param Config|array $config
* @param LoggerInterface $logger
* @param CacheItemPoolInterface|CacheInterface $cache
* @param TokenProvider $provider
* @param CacheAdapterFactory $cacheAdapterFactory
* @param Context|null $context
* @return ApiClient
*/
public function createClient(
$config,
LoggerInterface $logger = null,
$cache = null,
TokenProvider $provider = null,
CacheAdapterFactory $cacheAdapterFactory = null,
Context $context = null
) {
return $this->createCustomClient(
ApiClient::class,
$config,
$logger,
$cache,
$provider,
$cacheAdapterFactory,
$context
);
}
public function createAuthClient(
array $options = [],
CorrelationIdProvider $correlationIdProvider = null
) {
if (isset($options['handler']) && $options['handler'] instanceof HandlerStack) {
$handler = $options['handler'];
} else {
$handler = HandlerStack::create();
$options['handler'] = $handler;
}
$handler->remove("http_errors");
$handler->unshift(self::httpErrors(), 'ctp_http_errors');
$this->setCorrelationIdMiddleware($handler, $correlationIdProvider);
$options = $this->addMiddlewares($handler, $options);
return new Client($options);
}
private function getDefaultOptions(Config $config)
{
$options = $config->getClientOptions();
$options['http_errors'] = $config->getThrowExceptions();
$options['base_uri'] = $config->getApiUrl() . "/" . $config->getProject() . "/";
$defaultHeaders = [
'User-Agent' => (new UserAgentProvider())->getUserAgent()
];
if (!is_null($config->getAcceptEncoding())) {
$defaultHeaders['Accept-Encoding'] = $config->getAcceptEncoding();
}
$options['headers'] = array_merge($defaultHeaders, (isset($options['headers']) ? $options['headers'] : []));
return $options;
}
/**
* @param Config|array $config
* @return Config
* @throws InvalidArgumentException
*/
private function createConfig($config)
{
if ($config instanceof Config) {
return $config;
}
if (is_array($config)) {
return Config::fromArray($config);
}
throw new InvalidArgumentException();
}
/**
* @param string $clientClass
* @param array $options
* @param OAuth2Handler $oauthHandler
* @param LoggerInterface|null $logger
* @param CorrelationIdProvider|null $correlationIdProvider
* @return Client
*/
private function createGuzzle6Client(
$clientClass,
array $options,
OAuth2Handler $oauthHandler,
LoggerInterface $logger = null,
CorrelationIdProvider $correlationIdProvider = null
) {
if (isset($options['handler']) && $options['handler'] instanceof HandlerStack) {
$handler = $options['handler'];
} else {
$handler = HandlerStack::create();
$options['handler'] = $handler;
}
$options = array_merge(
[
'allow_redirects' => false,
'verify' => true,
'timeout' => 60,
'connect_timeout' => 10,
'pool_size' => 25,
],
$options
);
if (!is_null($logger)) {
$this->setLogger($handler, $logger);
}
$handler->remove("http_errors");
$handler->unshift(self::httpErrors(), 'ctp_http_errors');
$handler->push(
Middleware::mapRequest($oauthHandler),
'oauth_2_0'
);
if ($oauthHandler->refreshable()) {
$handler->push(
self::reauthenticate($oauthHandler),
'reauthenticate'
);
}
$this->setCorrelationIdMiddleware($handler, $correlationIdProvider);
$options = $this->addMiddlewares($handler, $options);
$client = new $clientClass($options);
return $client;
}
private function setLogger(
HandlerStack $handler,
LoggerInterface $logger,
$logLevel = LogLevel::INFO,
$formatter = null
) {
if (is_null($formatter)) {
$formatter = new MessageFormatter();
}
$handler->push(self::log($logger, $formatter, $logLevel), 'ctp_logger');
}
/**
* @param CorrelationIdProvider $correlationIdProvider
* @param HandlerStack $handler
*/
private function setCorrelationIdMiddleware(
HandlerStack $handler,
CorrelationIdProvider $correlationIdProvider = null
) {
if (!is_null($correlationIdProvider)) {
$handler->push(Middleware::mapRequest(function (RequestInterface $request) use ($correlationIdProvider) {
return $request->withAddedHeader(
AbstractApiResponse::X_CORRELATION_ID,
$correlationIdProvider->getCorrelationId()
);
}), 'ctp_correlation_id');
}
}
/**
* @param HandlerStack $handler
* @param array $options
* @return array
*/
private function addMiddlewares(HandlerStack $handler, array $options)
{
if (isset($options['middlewares']) && is_array($options['middlewares'])) {
foreach ($options['middlewares'] as $key => $middleware) {
if (is_callable($middleware)) {
if (!is_numeric($key)) {
$handler->remove($key);
$handler->push($middleware, $key);
} else {
$handler->push($middleware);
}
}
}
}
return $options;
}
/**
* Middleware that reauthenticates on invalid token error
*
* @param OAuth2Handler $oauthHandler
* @param int $maxRetries
* @return callable Returns a function that accepts the next handler.
*/
public static function reauthenticate(OAuth2Handler $oauthHandler, $maxRetries = 1)
{
return function (callable $handler) use ($oauthHandler, $maxRetries) {
return function (RequestInterface $request, array $options) use ($handler, $oauthHandler, $maxRetries) {
return $handler($request, $options)->then(
function (ResponseInterface $response) use (
$request,
$handler,
$oauthHandler,
$options,
$maxRetries
) {
if ($response->getStatusCode() == 401) {
if (!isset($options['reauth'])) {
$options['reauth'] = 0;
}
$exception = ApiException::create($request, $response);
if ($options['reauth'] < $maxRetries && $exception instanceof InvalidTokenException) {
$options['reauth']++;
$token = $oauthHandler->refreshToken();
$request = $request->withHeader(
'Authorization',
'Bearer ' . $token->getToken()
);
return $handler($request, $options);
}
}
return $response;
}
);
};
};
}
/**
* Middleware that throws exceptions for 4xx or 5xx responses when the
* "http_error" request option is set to true.
*
* @return callable Returns a function that accepts the next handler.
*/
public static function httpErrors()
{
return function (callable $handler) {
return function ($request, array $options) use ($handler) {
if (empty($options['http_errors'])) {
return $handler($request, $options);
}
return $handler($request, $options)->then(
function (ResponseInterface $response) use ($request, $handler) {
$code = $response->getStatusCode();
if ($code < 400) {
return $response;
}
throw ApiException::create($request, $response);
}
);
};
};
}
/**
* @param ClientCredentials $credentials
* @param string $accessTokenUrl
* @param CacheItemPoolInterface|CacheInterface $cache
* @param TokenProvider $provider
* @param array $authClientOptions
* @param CorrelationIdProvider|null $correlationIdProvider
* @return OAuth2Handler
*/
private function getHandler(
ClientCredentials $credentials,
$accessTokenUrl,
$cache,
TokenProvider $provider = null,
array $authClientOptions = [],
CorrelationIdProvider $correlationIdProvider = null
) {
if (is_null($provider)) {
$provider = new CredentialTokenProvider(
$this->createAuthClient($authClientOptions, $correlationIdProvider),
$accessTokenUrl,
$credentials
);
$cacheKey = sha1($credentials->getClientId() . $credentials->getScope());
$provider = new CacheTokenProvider($provider, $cache, $cacheKey);
}
return new OAuth2Handler($provider);
}
/**
* Middleware that logs requests, responses, and errors using a message
* formatter.
*
* @param LoggerInterface $logger Logs messages.
* @param MessageFormatter $formatter Formatter used to create message strings.
* @param string $logLevel Level at which to log requests.
*
* @return callable Returns a function that accepts the next handler.
*/
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 (ResponseInterface $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);
}
);
};
};
}
/**
* @return bool
*/
private static function isGuzzle6()
{
if (is_null(self::$isGuzzle6)) {
if (defined('\GuzzleHttp\Client::MAJOR_VERSION')) {
$clientVersion = (string) constant(HttpClient::class . '::MAJOR_VERSION');
} else {
$clientVersion = (string) constant(HttpClient::class . '::VERSION');
}
if (version_compare($clientVersion, '6.0.0', '>=')) {
self::$isGuzzle6 = true;
} else {
self::$isGuzzle6 = false;
}
}
return self::$isGuzzle6;
}
/**
* @return ClientFactory
*/
public static function of()
{
return new static();
}
}