Backend.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: tatu
  5. * Date: 6/22/20
  6. * Time: 9:58 PM
  7. */
  8. namespace App\Lib;
  9. use GuzzleHttp\Client as Guzzle;
  10. use GuzzleHttp\Cookie\CookieJar;
  11. use Psr\Http\Message\StreamInterface;
  12. use GuzzleHttp\Exception\ClientException;
  13. class Backend
  14. {
  15. protected $url;
  16. public function __construct()
  17. {
  18. $this->url = config('stag.backendUrl');
  19. }
  20. public function post(string $url, array $data, $headers = null)
  21. {
  22. return $this->sendRequest($url, 'POST', ['form_params' => $data, 'headers'=>$headers]);
  23. }
  24. public function get(string $url, array $data = [])
  25. {
  26. return $this->sendRequest($url, 'GET', $data);
  27. }
  28. /**
  29. * @param string $url
  30. * @param string $method HTTP request method eg POST, GET.
  31. * @param array $options
  32. * @return StreamInterface
  33. * @throws \GuzzleHttp\Exception\GuzzleException
  34. */
  35. public function sendRequest(string $url, string $method, array $options = []) : StreamInterface
  36. {
  37. $url = sprintf('%s/%s', rtrim($this->url, '/'), trim($url, '/'));
  38. $response = null;
  39. $client = new Guzzle();
  40. try {
  41. $response = $client->request($method, $url, $options);
  42. }
  43. catch (ClientException $clientException) {
  44. $response = $clientException->getResponse();
  45. }
  46. return $response->getBody();
  47. }
  48. }