Client.php 1.9 KB
<?php

namespace Lackoxygen\TiktokOpen\Base\Client;

use Lackoxygen\TiktokOpen\Application;
use Lackoxygen\TiktokOpen\Base\Event\Fail;
use Lackoxygen\TiktokOpen\Base\Event\Request;
use Lackoxygen\TiktokOpen\Base\Event\Response;
use Lackoxygen\TiktokOpen\Base\ServiceManager;
use Lackoxygen\TiktokOpen\Base\Signer\SignerInterface;
use Lackoxygen\TiktokOpen\Base\Traits\BaseClient;
use Lackoxygen\TiktokOpen\Wap\Listener;
use GuzzleHttp\RequestOptions;
use Illuminate\Support\Facades\Event;

class Client extends ServiceManager
{
    use BaseClient;

    private string $requestOption = '';

    private bool $withSession;

    private SignerInterface $signer;

    public function __construct(
        Application $app,
        $requestOption = '',
        $withSession = false
    ) {
        parent::__construct($app);

        $this->listen();

        $this->requestOption = $requestOption;

        $this->withSession = $withSession;
    }

    protected function listen()
    {
        Event::listen(Request::class, [Listener::class, 'request']);
        Event::listen(Response::class, [Listener::class, 'response']);
        Event::listen(Fail::class, [Listener::class, 'fail']);
    }


    public function asForm(): Client
    {
        return new Client($this->app, RequestOptions::FORM_PARAMS, $this->withSession);
    }

    public function asJson(): Client
    {
        return new Client($this->app, RequestOptions::JSON, $this->withSession);
    }

    public function asMultipart(): Client
    {
        return new Client($this->app, RequestOptions::MULTIPART, $this->withSession);
    }

    public function withSession(): Client
    {
        return new Client($this->app, $this->requestOption, true);
    }

    public function signVia(SignerInterface $signer): Client
    {
        $this->signer = $signer;

        return $this;
    }

    public function refresh()
    {
        $this->requestOption = '';
        $this->withSession   = false;
    }
}