Builder.php 2.4 KB
<?php

namespace Lackoxygen\TiktokShop\Transmit;

use Lackoxygen\TiktokShop\Attribute\Config;
use Lackoxygen\TiktokShop\Attribute\Request;
use Lackoxygen\TiktokShop\Exception\ClientException;
use Lackoxygen\TiktokShop\Mock\Mock;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Http\Message\ResponseInterface;

class Builder
{
    protected Request $request;

    protected Config $config;

    protected string $passage;

    protected string $method;

    public function __construct(Config $config, string $passage, string $method)
    {
        $this->request = new Request();
        $this->config = $config;
        $this->request->setConfig($config);
        $this->passage = $passage;
        $this->method = $method;
    }

    public static function create(Config $config, string $passage, string $method): Builder
    {
        return new static(...func_get_args());
    }

    public function method(string $method): Builder
    {
        $this->request->setMethod($method);
        return $this;
    }

    public function params(array $params): Builder
    {
        $this->request->setParams($params);
        return $this;
    }

    public function v(string $v): Builder
    {
        $this->request->setV($v);
        return $this;
    }

    public function timestamp($timestamp): Builder
    {
        $this->request->setTimestamp($timestamp);
        return $this;
    }

    public function service(?string $service): Builder
    {
        $this->request->setService($service);
        return $this;
    }

    public function signature(bool $signature): Builder
    {
        $this->request->setSignature($signature);
        return $this;
    }

    public function path(string $path): Builder
    {
        $this->request->setPath($path);
        return $this;
    }

    /**
     * @return Request
     */
    public function getRequest(): Request
    {
        return $this->request;
    }

    /**
     * @return ResponseInterface
     * @throws ClientException
     */
    public function request(): ResponseInterface
    {
        $client = Client::create();
        if ($this->config->isEnableMock()) {
            $mock = new Mock($this->passage, $this->method);
            return $mock->response();
        }
        try {
            return $client->request($this->request);
        } catch (GuzzleException $e) {
            throw new ClientException($e);
        }
    }
}