src/Service/ListingRotationApi.php line 36

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.         $topPlacement $this->profileTopBoard->currentTopPlacement(false);
  31.         $limit $apiLimit =  $this->onPageLimit;
  32.         $offset $apiOffset = ($pageNumber 1) * $limit;
  33.         if (null !== $topPlacement) {
  34.             if ($pageNumber === 1) {
  35.                 $apiLimit $this->onPageLimit 1;
  36.             } else {
  37.                 $apiOffset = ($pageNumber 1) * $limit 1;
  38.             }
  39.         }
  40.         $response $this->httpClient->request('GET'$this->buildUrl($endpoint$params), [
  41.             'query' => [
  42.                 'limit' => $apiLimit,
  43.                 'offset' => $apiOffset,
  44.             ],
  45.         ]);
  46.         $data json_decode($response->getBody()->getContents(), true);
  47.         $items $data['items'];
  48.         if (null !== $topPlacement && $pageNumber === 1) {
  49.             array_unshift($items$topPlacement);
  50.         }
  51.         return new ArrayPage($items$offset$limit$data['totalCount']);
  52.     }
  53.     private function buildUrl(string $endpoint, array $params): string
  54.     {
  55.         $url '/listings';
  56.         if (!str_starts_with($endpoint'/')) {
  57.             $url .= '/';
  58.         }
  59.         $url .= $endpoint;
  60.         $finalUrl preg_replace_callback('#\{\s*([a-z0-9_]+)\s*}#', static function ($matches) use ($params) {
  61.             return $params[$matches[1]] ?? $matches[0];
  62.         }, $url);
  63.         return $finalUrl;
  64.     }
  65. }