[ Index ] |
PHP Cross Reference of Phabricator |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * HTTP Stream version of the TinyHttp Client used to connect to Twilio 4 * services. 5 */ 6 7 class Services_Twilio_HttpStreamException extends ErrorException {} 8 9 class Services_Twilio_HttpStream { 10 11 private $auth_header = null; 12 private $uri = null; 13 private $debug = false; 14 private static $default_options = array( 15 "http" => array( 16 "headers" => "", 17 "timeout" => 60, 18 "follow_location" => true, 19 "ignore_errors" => true, 20 ), 21 "ssl" => array(), 22 ); 23 private $options = array(); 24 25 public function __construct($uri = '', $kwargs = array()) { 26 $this->uri = $uri; 27 if (isset($kwargs['debug'])) { 28 $this->debug = true; 29 } 30 if (isset($kwargs['http_options'])) { 31 $this->options = $kwargs['http_options'] + self::$default_options; 32 } else { 33 $this->options = self::$default_options; 34 } 35 } 36 37 public function __call($name, $args) { 38 list($res, $req_headers, $req_body) = $args + array(0, array(), ''); 39 40 $request_options = $this->options; 41 $url = $this->uri . $res; 42 43 if (isset($req_body) && strlen($req_body) > 0) { 44 $request_options['http']['content'] = $req_body; 45 } 46 47 foreach($req_headers as $key => $value) { 48 $request_options['http']['header'] .= sprintf("%s: %s\r\n", $key, $value); 49 } 50 51 if (isset($this->auth_header)) { 52 $request_options['http']['header'] .= $this->auth_header; 53 } 54 55 $request_options['http']['method'] = strtoupper($name); 56 $request_options['http']['ignore_errors'] = true; 57 58 if ($this->debug) { 59 error_log(var_export($request_options, true)); 60 } 61 $ctx = stream_context_create($request_options); 62 $result = file_get_contents($url, false, $ctx); 63 64 if (false === $result) { 65 throw new Services_Twilio_HttpStreamException( 66 "Unable to connect to service"); 67 } 68 69 $status_header = array_shift($http_response_header); 70 if (1 !== preg_match('#HTTP/\d+\.\d+ (\d+)#', $status_header, $matches)) { 71 throw new Services_Twilio_HttpStreamException( 72 "Unable to detect the status code in the HTTP result."); 73 } 74 75 $status_code = intval($matches[1]); 76 $response_headers = array(); 77 78 foreach($http_response_header as $header) { 79 list($key, $val) = explode(":", $header); 80 $response_headers[trim($key)] = trim($val); 81 } 82 83 return array($status_code, $response_headers, $result); 84 } 85 86 public function authenticate($user, $pass) { 87 if (isset($user) && isset($pass)) { 88 $this->auth_header = sprintf("Authorization: Basic %s", 89 base64_encode(sprintf("%s:%s", $user, $pass))); 90 } else { 91 $this->auth_header = null; 92 } 93 } 94 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
Generated: Sun Nov 30 09:20:46 2014 | Cross-referenced by PHPXref 0.7.1 |