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
1.8 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. $filename = $this->_testDataPath.preg_replace('/https?:\/\//', '', $url);
  29. if(!file_exists($filename)) {
  30. $filename = $this->_testDataPath.'404.response.txt';
  31. }
  32. $response = file_get_contents($filename);
  33. $split = explode("\r\n\r\n", $response);
  34. if(count($split) < 2) {
  35. throw new \Exception("Invalid file contents in test data, check that newlines are CRLF: $url");
  36. }
  37. $headers = array_shift($split);
  38. $body = implode("\r\n", $split);
  39. if(preg_match('/HTTP\/1\.1 (\d+)/', $headers, $match)) {
  40. $code = $match[1];
  41. }
  42. $headers = preg_replace('/HTTP\/1\.1 \d+ .+/', '', $headers);
  43. $parsedHeaders = self::parse_headers($headers);
  44. if(array_key_exists('Location', $parsedHeaders)) {
  45. $effectiveUrl = \mf2\resolveUrl($url, $parsedHeaders['Location']);
  46. } else {
  47. $effectiveUrl = $url;
  48. }
  49. return array(
  50. 'code' => $code,
  51. 'headers' => $parsedHeaders,
  52. 'body' => $body,
  53. 'error' => (isset($parsedHeaders['X-Test-Error']) ? $parsedHeaders['X-Test-Error'] : ''),
  54. 'error_description' => '',
  55. 'url' => $effectiveUrl
  56. );
  57. }
  58. }