Skip to content

Commit

Permalink
Merge pull request #693 from sandervanhooft/idempotency_tweaks
Browse files Browse the repository at this point in the history
Idempotency refactoring and fix
  • Loading branch information
sandervanhooft authored Jul 31, 2023
2 parents 71bb7e8 + 1f240b1 commit 58ba62b
Showing 1 changed file with 34 additions and 13 deletions.
47 changes: 34 additions & 13 deletions src/MollieApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -596,10 +596,9 @@ public function setIdempotencyKeyGenerator($generator)
}

/**
* @param \Mollie\Api\Idempotency\IdempotencyKeyGeneratorContract $generator
* @return \Mollie\Api\MollieApiClient
*/
public function clearIdempotencyKeyGenerator($generator)
public function clearIdempotencyKeyGenerator()
{
$this->idempotencyKeyGenerator = null;

Expand Down Expand Up @@ -667,17 +666,7 @@ public function performHttpCallToFullUrl($httpMethod, $url, $httpBody = null)
$headers['X-Mollie-Client-Info'] = php_uname();
}

if (in_array($httpMethod, [self::HTTP_POST, self::HTTP_PATCH, self::HTTP_DELETE])) {
if (! $this->idempotencyKey && $this->idempotencyKeyGenerator) {
$headers['Idempotency-Key'] = $this->idempotencyKeyGenerator->generate();
}

if ($this->idempotencyKey) {
$headers['Idempotency-Key'] = $this->idempotencyKey;
} elseif ($this->idempotencyKeyGenerator) {
$headers['Idempotency-Key'] = $this->idempotencyKeyGenerator->generate();
}
}
$headers = $this->applyIdempotencyKey($headers, $httpMethod);

$response = $this->httpClient->send($httpMethod, $url, $headers, $httpBody);

Expand All @@ -686,6 +675,38 @@ public function performHttpCallToFullUrl($httpMethod, $url, $httpBody = null)
return $response;
}

/**
* Conditionally apply the idempotency key to the request headers
*
* @param array $headers
* @param string $httpMethod
* @return array
*/
private function applyIdempotencyKey(array $headers, string $httpMethod)
{
if (! in_array($httpMethod, [self::HTTP_POST, self::HTTP_PATCH, self::HTTP_DELETE])) {
unset($headers['Idempotency-Key']);

return $headers;
}

if ($this->idempotencyKey) {
$headers['Idempotency-Key'] = $this->idempotencyKey;

return $headers;
}

if ($this->idempotencyKeyGenerator) {
$headers['Idempotency-Key'] = $this->idempotencyKeyGenerator->generate();

return $headers;
}

unset($headers['Idempotency-Key']);

return $headers;
}

/**
* Serialization can be used for caching. Of course doing so can be dangerous but some like to live dangerously.
*
Expand Down

0 comments on commit 58ba62b

Please sign in to comment.