Http.php
2 weeks ago
HttpTransportCurl.php
2 weeks ago
HttpTransportFopen.php
2 weeks ago
HttpTransportInterface.php
2 weeks ago
HttpTransportWp.php
2 weeks ago
HttpTransportCurl.php
74 lines
| 1 | <?php |
| 2 | |
| 3 | namespace LLAR\Core\Http; |
| 4 | |
| 5 | class HttpTransportCurl implements HttpTransportInterface { |
| 6 | |
| 7 | /** |
| 8 | * @param $url |
| 9 | * @param array $options |
| 10 | * |
| 11 | * @return array |
| 12 | */ |
| 13 | public function get( $url, $options = array() ) { |
| 14 | |
| 15 | if( !empty( $options['data'] ) ) { |
| 16 | $query_str = http_build_query( $options['data'] ); |
| 17 | $url .= "?{$query_str}"; |
| 18 | } |
| 19 | |
| 20 | $headers = !empty( $options['headers'] ) ? $options['headers'] : array(); |
| 21 | |
| 22 | return $this->request( $url, 'GET', $headers ); |
| 23 | } |
| 24 | |
| 25 | /** |
| 26 | * @param $url |
| 27 | * @param array $options |
| 28 | * |
| 29 | * @return array |
| 30 | */ |
| 31 | public function post( $url, $options = array() ) { |
| 32 | |
| 33 | $headers = !empty( $options['headers'] ) ? $options['headers'] : array(); |
| 34 | $data = !empty( $options['data'] ) ? $options['data'] : array(); |
| 35 | |
| 36 | return $this->request( $url, 'POST', $headers, $data ); |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * @param $url |
| 41 | * @param $method |
| 42 | * @param array $headers |
| 43 | * @param array $data |
| 44 | * |
| 45 | * @return array |
| 46 | */ |
| 47 | private function request( $url, $method, $headers = array(), $data = array() ) { |
| 48 | |
| 49 | $handle = curl_init( $url ); |
| 50 | |
| 51 | curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true ); |
| 52 | |
| 53 | if( $method === 'POST' ) { |
| 54 | curl_setopt($handle, CURLOPT_POST, true); |
| 55 | curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode( $data, JSON_FORCE_OBJECT ) ); |
| 56 | } |
| 57 | |
| 58 | if ( !empty( $headers ) ) { |
| 59 | curl_setopt($handle, CURLOPT_HTTPHEADER, $headers); |
| 60 | } |
| 61 | |
| 62 | $response = curl_exec( $handle ); |
| 63 | $response_status = curl_getinfo( $handle, CURLINFO_HTTP_CODE ); |
| 64 | $response_error = ( false === $response ) ? curl_error( $handle ) : null; |
| 65 | |
| 66 | curl_close( $handle ); |
| 67 | |
| 68 | return array( |
| 69 | 'data' => $response, |
| 70 | 'status' => intval( $response_status ), |
| 71 | 'error' => $response_error, |
| 72 | ); |
| 73 | } |
| 74 | } |