HTTP.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /**
  3. * HTTP driver performs external requests using the
  4. * pecl_http extension.
  5. *
  6. * NOTE: This driver is not used by default. To use it as default call:
  7. *
  8. * @package KO7\Request
  9. *
  10. * @copyright (c) 2007-2016 Kohana Team
  11. * @copyright (c) since 2016 Koseven Team
  12. * @license https://koseven.dev/LICENSE
  13. *
  14. */
  15. class KO7_Request_Client_HTTP extends Request_Client_External {
  16. /**
  17. * Sends the HTTP message [Request] to a remote server and processes
  18. * the response.
  19. *
  20. * @param Request $request request to send
  21. * @param Response $response response to send
  22. *
  23. * @throws Request_Exception
  24. *
  25. * @return Response
  26. */
  27. public function _send_message(Request $request, Response $response) : Response
  28. {
  29. // Instance a new Client
  30. $client = new http\Client;
  31. // Process cookies
  32. if ($cookies = $request->cookie())
  33. {
  34. $client->setCookies($cookies);
  35. }
  36. // Instance HTTP Request Object
  37. $http_request = new \http\Client\Request($request->method(), $request->uri());
  38. // Set custom cURL options
  39. if ($this->_options)
  40. {
  41. $http_request->setOptions($this->_options);
  42. }
  43. // Set headers
  44. if ( ! empty($headers = $request->headers()->getArrayCopy()))
  45. {
  46. $http_request->setHeaders($headers);
  47. }
  48. // Set query (?foo=bar&bar=foo)
  49. if ($query = $request->query())
  50. {
  51. $http_request->setQuery($query);
  52. }
  53. // Set the body
  54. // This will also add a Content-Type: application/x-www-form-urlencoded header unless you override it
  55. if ($body = $request->body())
  56. {
  57. $http_request->getBody()->append($body);
  58. }
  59. // Execute call, will throw an Runtime Exception if a stream is not available
  60. try
  61. {
  62. $client->enqueue($http_request)->send();
  63. }
  64. catch (\http\Exception\RuntimeException $e)
  65. {
  66. throw new Request_Exception($e->getMessage());
  67. }
  68. // Parse Response
  69. $http_response = $client->getResponse();
  70. // Build the response
  71. $response
  72. ->status($http_response->getResponseCode())
  73. ->headers($http_response->getHeaders())
  74. ->cookie($http_response->getCookies())
  75. ->body($http_response->getBody());
  76. return $response;
  77. }
  78. }