1 | <?php |
||
2 | |||
3 | /** |
||
4 | * Part of the AmazonGiftCode package. |
||
5 | * Author: Kashyap Merai <[email protected]> |
||
6 | * |
||
7 | */ |
||
8 | |||
9 | |||
10 | namespace kamerk22\AmazonGiftCode\Client; |
||
11 | |||
12 | |||
13 | use Illuminate\Http\JsonResponse; |
||
14 | use kamerk22\AmazonGiftCode\Exceptions\AmazonErrors; |
||
15 | |||
16 | class Client implements ClientInterface |
||
17 | { |
||
18 | |||
19 | /** |
||
20 | * |
||
21 | * @param string $url The URL being requested, including domain and protocol |
||
22 | * @param array $headers Headers to be used in the request |
||
23 | * @param array $params Can be nested for arrays and hashes |
||
24 | * |
||
25 | * |
||
26 | * @return String |
||
27 | */ |
||
28 | public function request($url, $headers, $params): string |
||
29 | { |
||
30 | $handle = curl_init($url); |
||
31 | curl_setopt($handle, CURLOPT_POST, true); |
||
32 | curl_setopt($handle, CURLOPT_HTTPHEADER, $headers); |
||
33 | // curl_setopt($handle, CURLOPT_FAILONERROR, true); |
||
34 | curl_setopt($handle, CURLOPT_POSTFIELDS, $params); |
||
35 | curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); |
||
36 | $result = curl_exec($handle); |
||
37 | |||
38 | if ($result === false) { |
||
39 | $err = curl_errno($handle); |
||
40 | $message = curl_error($handle); |
||
41 | $this->handleCurlError($url, $err, $message); |
||
42 | } |
||
43 | |||
44 | if (curl_getinfo($handle, CURLINFO_HTTP_CODE) !== JsonResponse::HTTP_OK) { |
||
45 | $err = curl_errno($handle); |
||
46 | $message = json_decode($result)->message; |
||
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
47 | throw AmazonErrors::getError($message, $err); |
||
48 | } |
||
49 | return $result; |
||
50 | |||
51 | } |
||
52 | |||
53 | private function handleCurlError($url, $errno, $message): void |
||
54 | { |
||
55 | switch ($errno) { |
||
56 | case CURLE_COULDNT_CONNECT: |
||
57 | case CURLE_COULDNT_RESOLVE_HOST: |
||
58 | case CURLE_OPERATION_TIMEOUTED: |
||
59 | $msg = "Could not connect to AWS ($url). Please check your " |
||
60 | . 'internet connection and try again.'; |
||
61 | break; |
||
62 | case CURLE_SSL_CACERT: |
||
63 | case CURLE_SSL_PEER_CERTIFICATE: |
||
64 | $msg = "Could not verify Stripe's SSL certificate. Please make sure " |
||
65 | . 'that your network is not intercepting certificates. ' |
||
66 | . "(Try going to $url in your browser.) " |
||
67 | . 'If this problem persists,'; |
||
68 | break; |
||
69 | case 0: |
||
70 | default: |
||
71 | $msg = 'Unexpected error communicating with AWS. ' . $message; |
||
72 | } |
||
73 | |||
74 | throw new \RuntimeException($msg); |
||
75 | } |
||
76 | } |