/
v.bolshakov
/
AIEcosystem-Testing
Обзор
Документация
Войти
/
v.bolshakov
/
AIEcosystem-Testing
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
dev
common/components/CurlTransport.php
288 строк
7 KB
Developer
Initial commit
03 авг 2026, 17:43
03 авг 2026, 17:43
7433917
Код
Авторство
О чём код?
<?php namespace common\components; use common\helpers\ArrayHelper; use common\helpers\UrlHelper; use Yii; use yii\base\Component; use yii\helpers\Console; use yii\helpers\VarDumper; use yii\httpclient\Client; use yii\httpclient\Request; use yii\httpclient\RequestEvent; use yii\httpclient\Response; /** * Обёртка для работы с HTTP запросами * * @author Dmitry E. Semenov <sde.tomsk@gmail.com> * @copyright Self (c) 2026 */ class CurlTransport extends Component { /** * Логин для авторизации * @var */ public $username; /** * Пароль для авторизации * @var */ public $password; /** * Токен авторизации * @var */ public $token; /** * Токен авторизации * @var */ public $apiKey; /** * Базовый УРЛ * @var null */ public $endpoint = null; /** * Файл в виде строки * @var null */ public $file = null; /** * Файл в бинарном в виде * @var null */ public $file_content = null; /** * Бибоиотека взаимодействия * @var Client */ private $_client; /** * Формат передачи данных * @var array */ protected $format = [ 'request' => Client::FORMAT_JSON, 'response' => Client::FORMAT_JSON, ]; /** * init http client */ public function init() { parent::init(); // setup http client $this->_client = new Client([ 'baseUrl' => $this->endpoint, 'transport' => 'yii\httpclient\CurlTransport', 'requestConfig' => [ 'format' => ArrayHelper::getValue($this->format, 'request', Client::FORMAT_JSON) ], 'responseConfig' => [ 'format' => ArrayHelper::getValue($this->format, 'response', Client::FORMAT_JSON) ], ]); $this->_client->on(Client::EVENT_BEFORE_SEND, function (RequestEvent $event) { if ($this->username and $this->password) { $this->log('Authorization: ' . $this->username); $event->request ->getHeaders() ->add('Authorization', 'Basic ' . base64_encode("$this->username:$this->password")); $this->log('Authorization by login and password'); } elseif ($this->token) { $event->request ->getHeaders() ->add('Authorization', $this->token); $this->log('Authorization by token'); } if ($this->apiKey) { $event->request ->getHeaders() ->add('apiKey', $this->apiKey); $this->log('SET apiKey'); } $this->log($event->request->getMethod() . ': ' . $event->request->getFullUrl()); }); $this->_client->on(Client::EVENT_AFTER_SEND, function (RequestEvent $event) { $this->log('statusCode: ' . $event->response->statusCode); $response = ''; try { $response = VarDumper::dumpAsString($event->response->content); } catch (\Exception $e) { $response = $e->getMessage(); } catch (\Throwable $e) { $response = $e->getMessage(); } $this->log('response: ' . $response, $event->response->isOk); }); } /** * Получить объект * @return Client */ public function getCurl() { return $this->_client; } /** * Обработка ответа * @param Response $r * @return bool */ protected function handleResponse($r) { return $r->isOk; } /** * @var Request $request * @var array $options */ protected function send($request, $options) { if (YII_ENV_DEV or YII_DEBUG) { $options = ArrayHelper::merge([ 'SSL_VERIFYHOST' => 0, 'SSL_VERIFYPEER' => 0 ], $options); } $r = $request ->setOptions($options) ->send(); $this->handleResponse($r); return $r; } /** * Отправить запрос * * @param $resource * @param $data * @param array $options * @return mixed */ public function post($resource, $data = null, $options = []) { $request = $this->_client->post($resource, $data); if ($this->file) { $request->addFile('file', $this->file, $data); } elseif ($this->file_content) { $request->addFileContent('file', $this->file_content, $data); } return $this->send($request, $options); } /** * Получить данные * * @param $resource * @param array $query * @param null $data * @param array $options * @return mixed */ public function get($resource, $query = [], $data = null, $options = []) { $url = $resource . UrlHelper::query($query, false); /** @var Request $request */ $request = $this->_client->get($url, $data); return $this->send($request, $options); } /** * Обновить данные * * @param $resource * @param $data * @param array $options * @return mixed */ public function put($resource, $data, $options = []) { $request = $this->_client->put($resource, $data); return $this->send($request, $options); } /** * Удалить данные * * @param $resource * @param null $data * @param array $options * @return mixed */ public function delete($resource, $data = null, $options = []) { $request = $this->_client->delete($resource, $data); return $this->send($request, $options); } /** * Логгирование * * @param $message * @param bool $status */ public static function log($message, $status = true) { if (PHP_SAPI == 'cli') { if ($status) { $message = Console::ansiFormat($message, [Console::FG_GREEN]); } else { $message = Console::ansiFormat($message, [Console::FG_RED]); } Console::stdout($message . PHP_EOL); } else { Yii::info($message, 'curl'); } } /** * Сформировать строку для запроса * * @param $query * @param array $params * @return string */ protected function buildQuery($query, $params = []) { $p = []; foreach ((array)$params as $name => $value) { $p['{' . $name . '}'] = $value; } $query = ($p === []) ? $query : strtr($query, $p); return $query; } }