DirectRequest.php 2.21 KB
<?php

namespace App\Service\Requests;

use App\Service\API\API;

/**
 * Class DirectRequest
 * @package App\Service\Requests
 *
 *
 */
class DirectRequest extends APIRequest
{

    protected $limit = 10000;
    protected $max_count = -1;

    private $url;

    function __construct()
    {
        parent::__construct(API::YANDEX);

        $this->url = config('api.yandex.url');
    }

    function slice($maxObjects): ?\App\Service\Contract\APIRequest
    {
        return null;
    }

    function next($offset)
    {
        if (!isset($this->params['Page'])) {
            $this->params['Page'] = [
                'Limit' =>  $this->limit,
                'Offset' =>  $offset
            ];
        }
        $this->params['Page']['Limit'] = $this->limit;
        $this->params['Page']['Offset'] = $offset;
    }

    function getUrl()
    {
        return $this->url . strtolower($this->getService());
    }

    function getBody()
    {
        $data = [
            'method' => $this->getMethod(),
            'params' => $this->getParams() ?? (object)[]
        ];
        return json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }

    function getHeaders()
    {
        return [
//            "Authorization: Bearer " . $this->getToken()->token,                    // OAuth-токен. Использование слова Bearer обязательно
            "Accept-Language: ru",                             // Язык ответных сообщений
            "Content-Type: application/json; charset=utf-8"    // Тип данных и кодировка запроса
        ];
    }

    function getRequest($service, $method)
    {
        $ns = str_replace("DirectRequest", "Direct", self::class);
        $class = $ns . "\\" . ucfirst($method) . ucfirst($service);
        if (class_exists($class)) {
            $request = new $class($this->getApi());
            $request->setToken($this->getToken());
            return $request;
        }
        throw new \Exception("Unknown Service or Method \"{$class}\"");
        return $this;
    }

    function getObjectsCount()
    {
        return $this->getMaxCount();
    }

    function getMaxCount()
    {
        return $this->max_count;
    }
}