選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

AbstractApi.php 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. namespace common\components;
  3. use GuzzleHttp\Client;
  4. use linslin\yii2\curl\Curl;
  5. use Psr\Http\Message\ResponseInterface;
  6. abstract class AbstractApi
  7. {
  8. public string $url;
  9. public array $auth;
  10. public function __construct(string $url, array $auth)
  11. {
  12. $this->url = $url;
  13. $this->auth = $auth;
  14. }
  15. protected function get(string $resource, array $data = [], bool $raw = false)
  16. {
  17. $client = $this->getClient();
  18. $client->setGetParams($data);
  19. return $client->get($this->buildUrl($resource), $raw);
  20. }
  21. protected function post(string $resource, array $data = [], bool $raw = true)
  22. {
  23. $client = $this->getClient();
  24. $client->setPostParams($data);
  25. return $client->post($this->buildUrl($resource), $raw);
  26. }
  27. protected function put(string $resource, array $data = [], bool $raw = true)
  28. {
  29. $client = $this->getClient();
  30. $client->setPostParams($data);
  31. return $client->put($this->buildUrl($resource), $raw);
  32. }
  33. private function getClient()
  34. {
  35. $curl = new Curl();
  36. $curl->setHeader($this->auth[0], $this->auth[1]);
  37. return $curl;
  38. }
  39. public function buildUrl(string $resource): string
  40. {
  41. return $this->url.$resource;
  42. }
  43. protected function getUrl(): string
  44. {
  45. return $this->url;
  46. }
  47. private function getAuth(): array
  48. {
  49. return $this->auth;
  50. }
  51. }