Backend.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 Psr\Http\Message\StreamInterface;
  11. use GuzzleHttp\Exception\ClientException;
  12. class Backend
  13. {
  14. protected $url;
  15. public function __construct()
  16. {
  17. $this->url = config('stag.backendUrl');
  18. }
  19. public function post(string $url, array $data)
  20. {
  21. return $this->sendRequest($url, 'POST', ['form_params' => $data]);
  22. }
  23. public function get(string $url, array $data = [])
  24. {
  25. return $this->sendRequest($url, 'GET', $data);
  26. }
  27. /**
  28. * @param string $url
  29. * @param string $method HTTP request method eg POST, GET.
  30. * @param array $options
  31. * @return StreamInterface
  32. * @throws \GuzzleHttp\Exception\GuzzleException
  33. */
  34. public function sendRequest(string $url, string $method, array $options = []) : StreamInterface
  35. {
  36. $url = sprintf('%s/%s', rtrim($this->url, '/'), trim($url, '/'));
  37. $response = null;
  38. $client = new Guzzle();
  39. try {
  40. $response = $client->request($method, $url, $options);
  41. }
  42. catch (ClientException $clientException) {
  43. $response = $clientException->getResponse();
  44. }
  45. return $response->getBody();
  46. }
  47. }