Skip to content

Commit

Permalink
Merge pull request #104 from DimionX/patch-1
Browse files Browse the repository at this point in the history
Upgrade Guzzle Promises Function API to Static API
  • Loading branch information
ackintosh committed Jun 16, 2023
2 parents add74da + 2b7d59b commit a4c08dc
Showing 1 changed file with 34 additions and 3 deletions.
37 changes: 34 additions & 3 deletions src/Ganesha/GuzzleMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,20 @@ class GuzzleMiddleware
*/
private $failureDetector;

/**
* Function name to be used for returning a rejected promise.
*
* @var string
*/
private string $rejectionForFunction;

/**
* Function name to be used for returning a promise.
*
* @var string
*/
private string $promiseForFunction;

public function __construct(
Ganesha $ganesha,
ServiceNameExtractorInterface $serviceNameExtractor = null,
Expand All @@ -34,6 +48,16 @@ public function __construct(
$this->ganesha = $ganesha;
$this->serviceNameExtractor = $serviceNameExtractor ?: new ServiceNameExtractor();
$this->failureDetector = $failureDetector ?: new AlwaysSuccessFailureDetector();

// We need to support both the static and function API of `guzzle/promises` for the time being.
// https://github.com/guzzle/promises#upgrading-from-function-api
if (class_exists('\GuzzleHttp\Promise\Create')) {
$this->rejectionForFunction = '\GuzzleHttp\Promise\Create::rejectionFor';
$this->promiseForFunction = '\GuzzleHttp\Promise\Create::promiseFor';
} else {
$this->rejectionForFunction = '\GuzzleHttp\Promise\rejection_for';
$this->promiseForFunction = '\GuzzleHttp\Promise\promise_for';
}
}

/**
Expand All @@ -46,7 +70,8 @@ public function __invoke(callable $handler): \Closure
$serviceName = $this->serviceNameExtractor->extract($request, $options);

if (!$this->ganesha->isAvailable($serviceName)) {
return \GuzzleHttp\Promise\rejection_for(
return call_user_func(
$this->rejectionForFunction,
new RejectedException(
sprintf('"%s" is not available', $serviceName)
)
Expand All @@ -62,11 +87,17 @@ function ($value) use ($serviceName) {
} else {
$this->ganesha->success($serviceName);
}
return \GuzzleHttp\Promise\promise_for($value);
return call_user_func(
$this->promiseForFunction,
$value
);
},
function ($reason) use ($serviceName) {
$this->ganesha->failure($serviceName);
return \GuzzleHttp\Promise\rejection_for($reason);
return call_user_func(
$this->rejectionForFunction,
$reason
);
}
);
};
Expand Down

0 comments on commit a4c08dc

Please sign in to comment.