Skip to content

Commit 73a4d1a

Browse files
committed
Add 30 seconds caching
1 parent a5b1d03 commit 73a4d1a

File tree

1 file changed

+32
-15
lines changed

1 file changed

+32
-15
lines changed

src/Repositories/PaymentMethodsRepository.php

Lines changed: 32 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,33 +6,50 @@
66

77
class PaymentMethodsRepository implements PaymentMethodsRepositoryInterface {
88
private $accountId;
9-
private MoneiClient $moneiClient;
9+
private MoneiClient $moneiClient;
1010

11-
public function __construct( string $accountId, MoneiClient $moneiClient) {
12-
$this->accountId = $accountId;
13-
$this->moneiClient = $moneiClient;
11+
public function __construct( string $accountId, MoneiClient $moneiClient ) {
12+
$this->accountId = $accountId;
13+
$this->moneiClient = $moneiClient;
1414
}
1515

1616
/**
1717
* Fetch payment methods from the API.
1818
*/
1919
private function fetchFromAPI(): ?array {
20-
if ( ! $this->accountId ) {
21-
return null;
22-
}
23-
try {
24-
$response = $this->moneiClient->paymentMethods->get( $this->accountId );
25-
} catch ( \Exception $e ) {
26-
$response = null;
27-
}
28-
29-
return json_decode($response, true);
20+
if ( ! $this->accountId ) {
21+
return null;
22+
}
23+
try {
24+
$response = $this->moneiClient->paymentMethods->get( $this->accountId );
25+
} catch ( \Exception $e ) {
26+
$response = null;
27+
}
28+
29+
return json_decode( $response, true );
3030
}
3131

3232
/**
3333
* Get payment methods (fetch from transient or API).
3434
*/
3535
public function getPaymentMethods(): array {
36-
return $this->fetchFromAPI() ?: array();
36+
$transientKey = $this->generateTransientKey( $this->accountId );
37+
$data = get_transient( $transientKey );
38+
39+
if ( ! $data ) {
40+
$data = $this->fetchFromAPI();
41+
if ( $data ) {
42+
set_transient( $transientKey, $data, 30 );
43+
}
44+
}
45+
46+
return $data ?: array();
47+
}
48+
49+
/**
50+
* Generate a transient key.
51+
*/
52+
private function generateTransientKey( string $key ): string {
53+
return 'payment_methods_' . md5( $key );
3754
}
3855
}

0 commit comments

Comments
 (0)