Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

LuRequest.php 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: robin
  5. * Date: 11/23/15
  6. * Time: 10:56 PM
  7. */
  8. namespace Luticate\Utils;
  9. use GuzzleHttp\Client;
  10. use GuzzleHttp\Exception\ClientException;
  11. use GuzzleHttp\Exception\RequestException;
  12. class LuRequest
  13. {
  14. /**
  15. * @param $method
  16. * @param $url
  17. * @param array $get
  18. * @param array $post
  19. * @param array $headers
  20. * @return LuRequestDbo
  21. */
  22. public static function request($method, $url, $get = [], $post = null, $headers = [])
  23. {
  24. $client = new Client();
  25. $options = [
  26. "headers" => $headers,
  27. "form_params" => $post
  28. ];
  29. foreach ($get as $key => $value) {
  30. $url .= (strpos($url, '?') === false ? "?" : "&") . urlencode($key) . "=" . urlencode($value);
  31. }
  32. $response = null;
  33. try {
  34. $response = $client->request($method, $url, $options);
  35. } catch (ClientException $e) {
  36. $response = $e->getResponse();
  37. LuLog::log($response->getBody());
  38. LuLog::log($e);
  39. } catch (RequestException $e) {
  40. $response = $e->getResponse();
  41. LuLog::log($response->getBody());
  42. LuLog::log($e);
  43. } catch (\Exception $e) {
  44. LuLog::log($e);
  45. }
  46. if (!is_null($response)) {
  47. $body = json_decode($response->getBody(), true);
  48. $request = LuRequestDbo::jsonDeserialize($body);
  49. $request->setStatusCode($response->getStatusCode());
  50. return $request;
  51. }
  52. $request = new LuRequestDbo();
  53. $request->setMessage("Failed to parse response");
  54. $request->setStatusCode(500);
  55. return $request;
  56. }
  57. public static function proxy($method, $url, $get = [], $post = null, $headers = [])
  58. {
  59. $response = LuRequest::request($method, $url, $get, $post, $headers);
  60. if ($response->getStatusCode() != 200) {
  61. abort($response->getStatusCode(), $response->getMessage());
  62. }
  63. return $response->getData();
  64. }
  65. }