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.

92 lines
2.5 KiB

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