ResultSet.php 1.3 KB
<?php

namespace Lackoxygen\TiktokShop\Passage;

use Lackoxygen\TiktokShop\Util\Json;
use GuzzleHttp\Psr7\Response;
use Illuminate\Support\Arr;

class ResultSet
{
    protected array $items = [];

    protected $result;

    public function __construct($result)
    {
        $this->result = $result;

        if ($this->isResponse()) {
            $this->items = Json::unmarshal($result->getBody()->getContents());
        } else {
            $this->items = is_array($result) ? $result : [$result];
        }
    }

    protected function isResponse(): bool
    {
        return $this->result instanceof Response;
    }


    public function toArray(): array
    {
        return $this->items;
    }

    public function isSuccess(): bool
    {
        $array = $this->toArray();

        if ($this->isResponse()) {
            return 10000 === $array['code'];
        }

        return true === Arr::first($array);
    }

    public function getMessage(): string
    {
        $array = $this->toArray();

        return (string)$array['message'] ?? '';
    }

    public function getData(): array
    {
        $array = $this->toArray();

        return (array)Arr::get($array, 'data', []);
    }

    public function get(string $key, $default = '')
    {
        return Arr::get($this->getData(), $key, $default);
    }
}