Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

AbstractApi.php 1.5KB

11 månader sedan
11 månader sedan
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. if(count($this->auth)) {
  37. $curl->setHeader($this->auth[0], $this->auth[1]);
  38. }
  39. return $curl;
  40. }
  41. public function buildUrl(string $resource): string
  42. {
  43. return $this->url.$resource;
  44. }
  45. protected function getUrl(): string
  46. {
  47. return $this->url;
  48. }
  49. private function getAuth(): array
  50. {
  51. return $this->auth;
  52. }
  53. }