BaseClient.php 1.6 KB
<?php

namespace Lackoxygen\TiktokOpen\Base\Traits;

use Lackoxygen\TiktokOpen\Base\Client\Request;
use Lackoxygen\TiktokOpen\Base\Event\Fail as FailEvent;
use Lackoxygen\TiktokOpen\Base\Event\Request as RequestEvent;
use Lackoxygen\TiktokOpen\Base\Event\Response as ResponseEvent;
use Lackoxygen\TiktokOpen\Base\Utils\Json;
use GuzzleHttp\Exception\ClientException;

trait BaseClient
{
    public function get($url, $params = [])
    {
        return $this->request('GET', $url, $params);
    }

    public function post($url, $params = [])
    {
        return $this->request('POST', $url, $params);
    }

    public function put($url, $params = [])
    {
        return $this->request('PUT', $url, $params);
    }

    public function delete($url, $params = [])
    {
        return $this->request('DELETE', $url, $params);
    }

    public function request(string $method, string $path, array $data = [])
    {
        $request = new Request(
            $method,
            $this->requestOption,
            $path,
            $data,
            $this->withSession,
            $this->signer
        );

        RequestEvent::dispatch($this->app, $request);

        try {
            $response = $this->app['guzzleHttp']->request(
                $method,
                $path,
                $request->toArray()
            );
            ResponseEvent::dispatch($response);
            $response->getBody()->rewind();
            return Json::unmarshal($response->getBody()->getContents());
        } catch (ClientException $exception) {
            FailEvent::dispatch($exception);
        } finally {
            $this->refresh();
        }
    }
}