src/Service/ListingRotationApi.php line 37

Open in your IDE?
  1. <?php
  2. namespace App\Service;
  3. use GuzzleHttp\ClientInterface;
  4. use Porpaginas\Arrays\ArrayPage;
  5. use Porpaginas\Page;
  6. class ListingRotationApi
  7. {
  8.     private ClientInterface $httpClient;
  9.     private int $onPageLimit;
  10.     private ProfileTopBoard $profileTopBoard;
  11.     public function __construct(ClientInterface $apiRotationClient$onPageLimitProfileTopBoard $profileTopBoard)
  12.     {
  13.         $this->httpClient $apiRotationClient;
  14.         $this->onPageLimit = (int)$onPageLimit;
  15.         $this->profileTopBoard $profileTopBoard;
  16.     }
  17.     /**
  18.      * @param string $endpoint Listing API endpoint
  19.      * @param array $params Набор динамических параметров для замены в URL
  20.      * @param int $pageNumber Номер текущей страницы
  21.      * @return Page
  22.      *
  23.      * @throws \GuzzleHttp\Exception\GuzzleException
  24.      */
  25.     public function paginate(string $endpoint, array $paramsint $pageNumber 1): Page
  26.     {
  27.         if ($pageNumber 1) {
  28.             $pageNumber 1;
  29.         }
  30.         $countTopCTR $pageNumber 1;
  31.         $topPlacement $this->profileTopBoard->currentTopPlacement($countTopCTR);
  32.         $limit $this->onPageLimit;
  33.         $offset = ($pageNumber 1) * $limit;
  34.         if (null !== $topPlacement) {
  35.             if ($pageNumber === 1) {
  36.                 $limit $this->onPageLimit 1;
  37.             } else {
  38.                 $offset = ($pageNumber 1) * $limit 1;
  39.             }
  40.         }
  41.         $response $this->httpClient->request('GET'$this->buildUrl($endpoint$params), [
  42.             'query' => [
  43.                 'limit' => $limit,
  44.                 'offset' => $offset,
  45.             ],
  46.         ]);
  47.         $data json_decode($response->getBody()->getContents(), true);
  48.         $items $data['items'];
  49.         if (null !== $topPlacement && $pageNumber === 1) {
  50.             array_unshift($items$topPlacement);
  51.         }
  52.         return new ArrayPage($items$data['offset'], $data['limit'], $data['totalCount']);
  53.     }
  54.     private function buildUrl(string $endpoint, array $params): string
  55.     {
  56.         $url '/listings';
  57.         if (!str_starts_with($endpoint'/')) {
  58.             $url .= '/';
  59.         }
  60.         $url .= $endpoint;
  61.         $finalUrl preg_replace_callback('#\{\s*([a-z0-9_]+)\s*}#', static function ($matches) use ($params) {
  62.             return $params[$matches[1]] ?? $matches[0];
  63.         }, $url);
  64.         return $finalUrl;
  65.     }
  66. }