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
HttpTransportWp.php
79 lines
| 1 | <?php |
| 2 | |
| 3 | namespace LLAR\Core\Http; |
| 4 | |
| 5 | class HttpTransportWp implements HttpTransportInterface { |
| 6 | |
| 7 | /** |
| 8 | * @param $url |
| 9 | * @param array $options |
| 10 | * |
| 11 | * @return array |
| 12 | */ |
| 13 | public function get( $url, $options = array() ) { |
| 14 | $response = wp_remote_get( $url, array( |
| 15 | 'headers' => !empty( $options['headers'] ) ? $this->format_headers( $options['headers'] ) : array(), |
| 16 | 'body' => !empty( $options['data'] ) ? $options['data'] : array() |
| 17 | ) ); |
| 18 | |
| 19 | return $this->prepare_response( $response ); |
| 20 | } |
| 21 | |
| 22 | /** |
| 23 | * @param $url |
| 24 | * @param array $options |
| 25 | * |
| 26 | * @return array |
| 27 | */ |
| 28 | public function post( $url, $options = array() ) { |
| 29 | $response = wp_remote_post( $url, array( |
| 30 | 'headers' => !empty( $options['headers'] ) ? $this->format_headers( $options['headers'] ) : array(), |
| 31 | 'body' => !empty( $options['data'] ) ? json_encode( $options['data'], JSON_FORCE_OBJECT ) : null |
| 32 | ) ); |
| 33 | |
| 34 | return $this->prepare_response( $response ); |
| 35 | } |
| 36 | |
| 37 | /** |
| 38 | * @param $response |
| 39 | * |
| 40 | * @return array |
| 41 | */ |
| 42 | private function prepare_response( $response ) { |
| 43 | |
| 44 | $return = array( |
| 45 | 'data' => null, |
| 46 | 'status' => 0, |
| 47 | 'error' => null |
| 48 | ); |
| 49 | |
| 50 | if( is_wp_error( $response ) ) { |
| 51 | $return['error'] = $response->get_error_message(); |
| 52 | } else { |
| 53 | $return['data'] = wp_remote_retrieve_body( $response ); |
| 54 | $return['status'] = intval( wp_remote_retrieve_response_code( $response ) ); |
| 55 | } |
| 56 | |
| 57 | return $return; |
| 58 | } |
| 59 | |
| 60 | /** |
| 61 | * @param array $headers |
| 62 | * |
| 63 | * @return array |
| 64 | */ |
| 65 | private function format_headers( $headers = array() ) { |
| 66 | |
| 67 | $formatted_headers = array(); |
| 68 | |
| 69 | if( !empty( $headers ) ) { |
| 70 | foreach ( $headers as $header ) { |
| 71 | list( $name, $value ) = explode( ':', $header ); |
| 72 | |
| 73 | $formatted_headers[ trim( $name ) ] = trim( $value ); |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | return $formatted_headers; |
| 78 | } |
| 79 | } |