You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
2.2 KiB

  1. <?php
  2. namespace Telegraph;
  3. class HTTPTest {
  4. public static function get($url) {
  5. return self::_read_file($url);
  6. }
  7. public static function post($url, $body, $headers=array()) {
  8. return self::_read_file($url);
  9. }
  10. public static function head($url) {
  11. $response = self::_read_file($url);
  12. return array(
  13. 'code' => $response['code'],
  14. 'headers' => $response['headers']
  15. );
  16. }
  17. private static function _read_file($url) {
  18. $filename = dirname(__FILE__).'/../tests/data/'.preg_replace('/https?:\/\//', '', $url);
  19. if(!file_exists($filename)) {
  20. $filename = dirname(__FILE__).'/../tests/data/404.response.txt';
  21. }
  22. $response = file_get_contents($filename);
  23. $split = explode("\r\n\r\n", $response);
  24. if(count($split) != 2) {
  25. throw new \Exception("Invalid file contents in test data, check that newlines are CRLF: $url");
  26. }
  27. list($headers, $body) = $split;
  28. if(preg_match('/HTTP\/1\.1 (\d+)/', $headers, $match)) {
  29. $code = $match[1];
  30. }
  31. $headers = preg_replace('/HTTP\/1\.1 \d+ .+/', '', $headers);
  32. return array(
  33. 'code' => $code,
  34. 'headers' => self::parse_headers($headers),
  35. 'body' => $body
  36. );
  37. }
  38. public static function parse_headers($headers) {
  39. $retVal = array();
  40. $fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $headers));
  41. foreach($fields as $field) {
  42. if(preg_match('/([^:]+): (.+)/m', $field, $match)) {
  43. $match[1] = preg_replace_callback('/(?<=^|[\x09\x20\x2D])./', function($m) {
  44. return strtoupper($m[0]);
  45. }, strtolower(trim($match[1])));
  46. // If there's already a value set for the header name being returned, turn it into an array and add the new value
  47. $match[1] = preg_replace_callback('/(?<=^|[\x09\x20\x2D])./', function($m) {
  48. return strtoupper($m[0]);
  49. }, strtolower(trim($match[1])));
  50. if(isset($retVal[$match[1]])) {
  51. if(!is_array($retVal[$match[1]]))
  52. $retVal[$match[1]] = array($retVal[$match[1]]);
  53. $retVal[$match[1]][] = $match[2];
  54. } else {
  55. $retVal[$match[1]] = trim($match[2]);
  56. }
  57. }
  58. }
  59. return $retVal;
  60. }
  61. }