|
- <?php
-
- namespace common\components;
-
- use GuzzleHttp\Client;
- use linslin\yii2\curl\Curl;
- use Psr\Http\Message\ResponseInterface;
-
- abstract class AbstractApi
- {
- public string $url;
- public array $auth;
-
- public function __construct(string $url, array $auth = [])
- {
- $this->url = $url;
- $this->auth = $auth;
- }
-
- protected function get(string $resource, array $data = [], bool $raw = false)
- {
- $client = $this->getClient();
- $client->setGetParams($data);
- return $client->get($this->buildUrl($resource), $raw);
- }
-
- protected function post(string $resource, array $data = [], bool $raw = true)
- {
- $client = $this->getClient();
- $client->setPostParams($data);
- return $client->post($this->buildUrl($resource), $raw);
- }
-
- protected function put(string $resource, array $data = [], bool $raw = true)
- {
- $client = $this->getClient();
- $client->setPostParams($data);
- return $client->put($this->buildUrl($resource), $raw);
- }
-
- private function getClient()
- {
- $curl = new Curl();
-
- if(count($this->auth)) {
- $curl->setHeader($this->auth[0], $this->auth[1]);
- }
-
- return $curl;
- }
-
- public function buildUrl(string $resource): string
- {
- return $this->url.$resource;
- }
-
- protected function getUrl(): string
- {
- return $this->url;
- }
-
- private function getAuth(): array
- {
- return $this->auth;
- }
- }
|