Skip to content

Commit

Permalink
Refactor and explicitly drop key on non-mutating requests
Browse files Browse the repository at this point in the history
  • Loading branch information
sandervanhooft committed Jul 31, 2023
1 parent f245437 commit 1f240b1
Showing 1 changed file with 33 additions and 11 deletions.
44 changes: 33 additions & 11 deletions src/MollieApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -666,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 @@ -685,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 1f240b1

Please sign in to comment.