|
6 | 6 |
|
7 | 7 | class PaymentMethodsRepository implements PaymentMethodsRepositoryInterface { |
8 | 8 | private $accountId; |
9 | | - private MoneiClient $moneiClient; |
| 9 | + private MoneiClient $moneiClient; |
10 | 10 |
|
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; |
14 | 14 | } |
15 | 15 |
|
16 | 16 | /** |
17 | 17 | * Fetch payment methods from the API. |
18 | 18 | */ |
19 | 19 | 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 ); |
30 | 30 | } |
31 | 31 |
|
32 | 32 | /** |
33 | 33 | * Get payment methods (fetch from transient or API). |
34 | 34 | */ |
35 | 35 | 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 ); |
37 | 54 | } |
38 | 55 | } |
0 commit comments