params[$apiName]: `protocol` (`http://` | `https://`), * `baseUrl`, `defaultVersion`, `defaultPerPage`, имена параметров страницы * `pageParam`/`perPageParam`, и по версиям — `version[][url]` с набором * `functions[<имя>]` (`url` — строка или массив с ключами `url`/`method`/ * `perPage`/`content`; `content` — ключ ответа, в котором лежит список). * Итоговый URL: protocol + baseUrl + version.url + url функции, в которую * через vsprintf подставляются $urlParams. */ class Swagger { /** @var string собранный адрес эндпоинта */ private $url; /** @var string HTTP-метод запроса (GET | POST) */ private $method; /** @var int размер страницы */ private $perPage; /** @var string имя query-параметра количества элементов на странице */ private $perPageParam; /** @var string имя query-параметра номера страницы */ private $pageParam; /** @var array фильтры/тело запроса */ private $params; /** @var string ключ ответа, в котором содержится список элементов */ private $content; /** @var int номер следующей страницы (счётчик getNextPage) */ private $currentPage = 1; /** @var bool достигнута ли последняя страница */ private $lastPage = false; /** @var bool передавать $params как есть, без обёртки `filter` */ public $isRaw = false; /** * @param string $apiName имя конфигурации сервиса в Yii::$app->params * @param string $function имя функции (эндпоинта) в конфиге версии * @param array $params фильтры/тело запроса * @param array $urlParams подстановки в url функции (vsprintf) * @param string|false $version версия API, иначе defaultVersion из конфига * @param bool $raw режим сырых параметров (без обёртки `filter`) * @throws Exception при неполной конфигурации или неизвестной функции */ function __construct($apiName, $function, $params = [], $urlParams = [], $version = false, $raw = false) { $arConfig = $this->getConfig($apiName, $function, $urlParams, $version); $this->url = $arConfig['url']; $this->method = $arConfig['method']; $this->perPage = $arConfig['perPage']; $this->perPageParam = $arConfig['perPageParam']; $this->pageParam = $arConfig['pageParam']; $this->content = $arConfig['content']; $this->params = $params; $this->isRaw = $raw; } /** * Проверяет конфигурацию сервиса и собирает параметры запроса: итоговый * url, method (функция → версия → GET), perPage (функция → defaultPerPage) * и имена пагинационных параметров. * * @param string $apiName * @param string $function * @param array $urlParams * @param string|false $version * @return array url/method/perPage/perPageParam/pageParam/content * @throws Exception на любую недостающую настройку */ private function getConfig($apiName, $function, $urlParams = [], $version = false) { $configParams = isset(Yii::$app->params[$apiName]) ? Yii::$app->params[$apiName] : []; if(empty($configParams)) { throw new Exception('Отсутствует конфигурация для rest-сервиса'); } if(!isset($configParams['defaultVersion']) or (empty($configParams['defaultVersion']))) { throw new Exception('Отсутствует дефолтная версия для rest-сервиса'); } if(!isset($configParams['defaultPerPage']) or (empty($configParams['defaultPerPage']))) { throw new Exception('Отсутствует дефолтная конфигурация постраничной навигации rest-сервиса'); } if(!isset($configParams['protocol']) or empty($configParams['protocol'])) { throw new Exception('Протокол rest-сервиса не указан.'); } if(($configParams['protocol'] !== 'http://') and ($configParams['protocol'] !== 'https://')) { throw new Exception('Протокол rest-сервиса указан неверно.'); } if(!isset($configParams['perPageParam']) or empty($configParams['perPageParam'])) { throw new Exception('Отсутствует параметр постраничной навигации perPageParam.'); } if(!isset($configParams['pageParam']) or empty($configParams['pageParam'])) { throw new Exception('Отсутствует парамер постраничной навигации pageParam.'); } if(!isset($configParams['baseUrl']) or empty($configParams['baseUrl'])) { throw new Exception('Отсутствует доменное имя для rest-сервиса.'); } if(empty($version)) { $version = $configParams['defaultVersion']; } if(empty($configParams['version'][$version])) { throw new Exception('Выбранная версия rest-сервиса отсутствует'); } if(!isset($configParams['version'][$version]['functions'][$function])) { throw new Exception('Функция '.$function.' отсутствует в api версии '.$version); } $url = ''; if(is_string($configParams['version'][$version]['functions'][$function])) { $url = $configParams['version'][$version]['functions'][$function]; } elseif(isset($configParams['version'][$version]['functions'][$function]['url'])) { $url = $configParams['version'][$version]['functions'][$function]['url']; } if(!isset($url) or empty($url)) { throw new Exception('Для функции '.$function.' отсутствует url'); } if(isset($configParams['version'][$version]['functions'][$function]['content'])) { $content = $configParams['version'][$version]['functions'][$function]['content']; } else { $content = $configParams['version'][$version]['content']; } if(!isset($content) or empty($content)) { throw new Exception('Для функции '.$function.' отсутствует ключ массива в котором содержится ответ'); } if(!isset($configParams['version'][$version]['functions'][$function]['perPage']) or empty($configParams['version'][$version]['functions'][$function]['perPage'])) { $perPage = $configParams['defaultPerPage']; } else { $perPage = $configParams['version'][$version]['functions'][$function]['perPage']; } if(!isset($configParams['version'][$version]['functions'][$function]['method']) or empty($configParams['version'][$version]['functions'][$function]['method'])) { $method = isset($configParams['version'][$version]['method']) ? $configParams['version'][$version]['method'] : 'GET'; } else { $method = $configParams['version'][$version]['functions'][$function]['method']; } if(!empty($urlParams)) { $url = vsprintf($url, $urlParams); } return [ 'url' => $configParams['protocol'] .$configParams['baseUrl'] .$configParams['version'][$version]['url'] .$url, 'method' => $method, 'perPage' => $perPage, 'perPageParam' => $configParams['perPageParam'], 'pageParam' => $configParams['pageParam'], 'content' => $content, ]; } /** * Сбрасывает счётчик страниц — следующий getNextPage() начнёт с первой. */ public function resetCounter() { $this->currentPage = 1; $this->lastPage = false; } /** * Возвращает следующую страницу списка и сдвигает внутренний счётчик; * последняя страница определяется по `_meta.pageCount` ответа (или по его * отсутствию). Вызывать в цикле до false. * * @return array|false элементы страницы либо false после последней страницы */ public function getNextPage() { if($this->lastPage) return false; $result = []; $response = $this->sendRequest($this->currentPage); if(isset($response[$this->content])) { foreach ($response[$this->content] as $value) { $result[] = $value; } } if( !isset($response['_meta']['pageCount']) or empty($response['_meta']['pageCount']) or $response['_meta']['pageCount'] === $this->currentPage ) { $this->lastPage = true; } else { $this->currentPage++; } return $result; } /** * Первый элемент следующей страницы (или false, если страниц не осталось). * * @return mixed|false */ public function getOne() { $result = $this->getNextPage(); return isset($result[0]) ? $result[0] : false; } /** * Пролистывает сервис до конца и собирает весь список в один массив: * остановка на пустом `content` или на `_meta.pageCount`. * * @return array */ public function doBatchRequest() { $result = []; $page = 1; while(true) { $response = $this->sendRequest($page); if (isset($response[$this->content]) and is_array($response[$this->content]) and !empty($response[$this->content]) ) { foreach ($response[$this->content] as $value) { $result[] = $value; } } else { return $result; } if( !isset($response['_meta']['pageCount']) or empty($response['_meta']['pageCount']) or $response['_meta']['pageCount'] === $page ) { break; } unset($response); $page++; } return $result; } /** * Тело POST-запроса: $params как есть при isRaw, иначе обёрнутые в `filter`. * * @return string */ public function getBody() { return $this->isRaw ? json_encode($this->params) : json_encode(['filter' => $this->params]) ; } /** * Запрос одной страницы: POST (пагинация в query, фильтры в теле) или * GET (всё в query, фильтры под ключом `filter`); таймаут и HTTP-коды, * кроме 200, превращаются в исключения. * * @param int $page * @return array декодированный ответ * @throws Exception на неподдерживаемый метод и на ошибки транспорта */ private function sendRequest($page = 1) { $curl = new curl\Curl(); $curl->setHeader('Content-Type', 'application/json; charset=UTF-8'); $params = [$this->perPageParam => $this->perPage, $this->pageParam => $page]; if (!empty($this->sort)) { $params['sort'] = $this->sort; } if($this->method === 'POST') { $curl->setGetParams($params); if(!empty($this->params)) { $curl->setRequestBody($this->getBody()); } $response = $curl->post($this->url,false); } elseif($this->method === 'GET') { $curl->setGetParams(array_merge($params, ['filter' => $this->params])); $response = $curl->get($this->url,false); } else { throw new Exception('Метод '.$this->method.' не поддерживается'); } switch ($curl->responseCode) { case 'timeout': throw new Exception('Network timeout'); break; case 200: return $response; break; case 404: throw new Exception('404. Page not found '. $this->url . ' ' . $this->getBody()); break; case 403: throw new Exception('403. Access deny '. $this->url . ' ' . $this->getBody()); break; case 401: throw new Exception('401. Autorization required '. $this->url . ' ' . $this->getBody()); break; case 400: throw new Exception('400. Bad request '. $this->url . ' ' . $this->getBody()); break; case 500: throw new Exception('500. Internal server error '. $this->url . ' ' . $this->getBody()); break; case 503: throw new Exception('503. Service unavailable '. $this->url . ' ' . $this->getBody()); break; case 502: throw new Exception('502. Bad gateway '. $this->url . ' ' . $this->getBody()); break; } } /** * Задаёт query-параметр `sort` для всех последующих запросов. * Внимание: свойство $sort в классе не объявлено — на PHP 8.2+ это * dynamic property (deprecated). * * @param string $str */ public function setSort($str) { $this->sort = $str; } }