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.

77 lines
2.0 KiB

  1. <?php
  2. namespace p3k;
  3. class HTTPTest extends HTTPCurl {
  4. private $_testDataPath;
  5. public function __construct($testDataPath) {
  6. $this->_testDataPath = $testDataPath;
  7. }
  8. public function get($url, $headers=[]) {
  9. $parts = parse_url($url);
  10. unset($parts['fragment']);
  11. $url = \build_url($parts);
  12. return $this->_read_file($url);
  13. }
  14. public function post($url, $body, $headers=[]) {
  15. return $this->_read_file($url);
  16. }
  17. public function head($url) {
  18. $response = $this->_read_file($url);
  19. return array(
  20. 'code' => $response['code'],
  21. 'headers' => $response['headers'],
  22. 'error' => '',
  23. 'error_description' => '',
  24. 'url' => $response['url']
  25. );
  26. }
  27. private function _read_file($url) {
  28. $parts = parse_url($url);
  29. if($parts['path']) {
  30. $parts['path'] = '/'.str_replace('/','_',substr($parts['path'],1));
  31. $url = \build_url($parts);
  32. }
  33. $filename = $this->_testDataPath.preg_replace('/https?:\/\//', '', $url);
  34. if(!file_exists($filename)) {
  35. $filename = $this->_testDataPath.'404.response.txt';
  36. }
  37. $response = file_get_contents($filename);
  38. $split = explode("\r\n\r\n", $response);
  39. if(count($split) < 2) {
  40. throw new \Exception("Invalid file contents in test data, check that newlines are CRLF: $url");
  41. }
  42. $headers = array_shift($split);
  43. $body = implode("\r\n", $split);
  44. if(preg_match('/HTTP\/1\.1 (\d+)/', $headers, $match)) {
  45. $code = $match[1];
  46. }
  47. $headers = preg_replace('/HTTP\/1\.1 \d+ .+/', '', $headers);
  48. $parsedHeaders = self::parse_headers($headers);
  49. if(array_key_exists('Location', $parsedHeaders)) {
  50. $effectiveUrl = \mf2\resolveUrl($url, $parsedHeaders['Location']);
  51. } else {
  52. $effectiveUrl = $url;
  53. }
  54. return array(
  55. 'code' => $code,
  56. 'headers' => $parsedHeaders,
  57. 'body' => $body,
  58. 'error' => (isset($parsedHeaders['X-Test-Error']) ? $parsedHeaders['X-Test-Error'] : ''),
  59. 'error_description' => '',
  60. 'url' => $effectiveUrl
  61. );
  62. }
  63. }