|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Http\Controllers; |
| 4 | + |
| 5 | +use http\Env\Request; |
| 6 | + |
| 7 | +ini_set('memory_limit', '1GB'); |
| 8 | + |
| 9 | +class ExampleController extends Controller |
| 10 | +{ |
| 11 | + |
| 12 | + private $apiUrl = "https://coronavirus-monitor.p.rapidapi.com/coronavirus/"; |
| 13 | + private $headerVars = array( |
| 14 | + "x-rapidapi-host: coronavirus-monitor.p.rapidapi.com", |
| 15 | + "x-rapidapi-key: 9a182b9ddamshef0fdd8891477ebp175fb9jsna8d94bc01b0c" |
| 16 | + ); |
| 17 | + |
| 18 | + private $validsEndpoints = array('affected', 'cases_by_country', 'usastates'); |
| 19 | + |
| 20 | + /** |
| 21 | + * Create a new controller instance. |
| 22 | + * |
| 23 | + * @return void |
| 24 | + */ |
| 25 | + public function __construct() |
| 26 | + { |
| 27 | + |
| 28 | + header('Content-Type: application/json'); |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * @param $type |
| 33 | + * |
| 34 | + * @return false|string |
| 35 | + */ |
| 36 | + public function getData($type = 'affected') |
| 37 | + { |
| 38 | + |
| 39 | + if (in_array($type, $this->validsEndpoints)) { |
| 40 | + |
| 41 | + $result = $this->connectApi($type); |
| 42 | + |
| 43 | + if (!empty($result['error'])) { |
| 44 | + echo json_encode($result); |
| 45 | + } |
| 46 | + |
| 47 | + echo $result; |
| 48 | + |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + return response(array('error' => true, 'message' => 'not found'), 404); |
| 53 | + |
| 54 | + } |
| 55 | + |
| 56 | + |
| 57 | + /** |
| 58 | + * @param $type |
| 59 | + * |
| 60 | + * @return array |
| 61 | + */ |
| 62 | + public function connectApi($type) |
| 63 | + { |
| 64 | + |
| 65 | + $curl = curl_init(); |
| 66 | + |
| 67 | + curl_setopt_array($curl, array( |
| 68 | + CURLOPT_URL => $this->apiUrl . $type . '.php', |
| 69 | + CURLOPT_RETURNTRANSFER => true, |
| 70 | + CURLOPT_FOLLOWLOCATION => true, |
| 71 | + CURLOPT_ENCODING => "", |
| 72 | + CURLOPT_MAXREDIRS => 10, |
| 73 | + CURLOPT_TIMEOUT => 30, |
| 74 | + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, |
| 75 | + CURLOPT_CUSTOMREQUEST => "GET", |
| 76 | + CURLOPT_HTTPHEADER => $this->headerVars, |
| 77 | + )); |
| 78 | + |
| 79 | + $response = curl_exec($curl); |
| 80 | + $err = curl_error($curl); |
| 81 | + |
| 82 | + curl_close($curl); |
| 83 | + |
| 84 | + if ($err) { |
| 85 | + return array('error' => true, 'message' => "cURL Error #:" . $err); |
| 86 | + } |
| 87 | + |
| 88 | + return $response; |
| 89 | + |
| 90 | + } |
| 91 | +} |
0 commit comments