MollieResponse.php
103 lines
| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * @copyright © Melograno Ventures. All rights reserved. |
| 5 | * @licence See LICENCE.md for license details. |
| 6 | */ |
| 7 | |
| 8 | namespace AmeliaBooking\Infrastructure\Services\Mollie; |
| 9 | |
| 10 | /** |
| 11 | * Class MollieResponse |
| 12 | * |
| 13 | * @package AmeliaBooking\Infrastructure\Services\Mollie |
| 14 | */ |
| 15 | class MollieResponse |
| 16 | { |
| 17 | /** |
| 18 | * HTTP status codes that indicate a successful API call. |
| 19 | */ |
| 20 | private const SUCCESS_CODES = [200, 201, 204]; |
| 21 | |
| 22 | /** |
| 23 | * @var array |
| 24 | */ |
| 25 | private array $data; |
| 26 | |
| 27 | /** |
| 28 | * @var int |
| 29 | */ |
| 30 | private int $httpCode; |
| 31 | |
| 32 | /** |
| 33 | * MollieResponse constructor. |
| 34 | */ |
| 35 | public function __construct(array $data) |
| 36 | { |
| 37 | $this->data = $data; |
| 38 | $this->httpCode = isset($data['_http_code']) ? (int)$data['_http_code'] : 0; |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * Whether the API call was successful. |
| 43 | */ |
| 44 | public function isSuccessful(): bool |
| 45 | { |
| 46 | return in_array($this->httpCode, self::SUCCESS_CODES, true); |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * Return the HTTP status code. |
| 51 | */ |
| 52 | public function getCode(): int |
| 53 | { |
| 54 | return $this->httpCode; |
| 55 | } |
| 56 | |
| 57 | /** |
| 58 | * True when the payment has a hosted checkout URL to redirect to. |
| 59 | */ |
| 60 | public function isRedirect(): bool |
| 61 | { |
| 62 | return !empty($this->data['_links']['checkout']['href']); |
| 63 | } |
| 64 | |
| 65 | /** |
| 66 | * The Mollie hosted checkout URL. |
| 67 | */ |
| 68 | public function getRedirectUrl(): string |
| 69 | { |
| 70 | return $this->data['_links']['checkout']['href'] ?? ''; |
| 71 | } |
| 72 | |
| 73 | /** |
| 74 | * Payment status string returned by Mollie (e.g. "open", "paid", "failed"). |
| 75 | */ |
| 76 | public function getStatus(): string |
| 77 | { |
| 78 | $status = $this->data['status'] ?? ''; |
| 79 | |
| 80 | return is_string($status) ? $status : (string)$status; |
| 81 | } |
| 82 | |
| 83 | /** |
| 84 | * Return a human-readable error message from the response, if any. |
| 85 | */ |
| 86 | public function getMessage(): string |
| 87 | { |
| 88 | if (!empty($this->data['detail'])) { |
| 89 | return $this->data['detail']; |
| 90 | } |
| 91 | |
| 92 | return $this->data['title'] ?? $this->data['message'] ?? ''; |
| 93 | } |
| 94 | |
| 95 | /** |
| 96 | * Return the raw Mollie API response array (includes `_http_code`). |
| 97 | */ |
| 98 | public function getData(): array |
| 99 | { |
| 100 | return $this->data; |
| 101 | } |
| 102 | } |
| 103 |