ResultSet.php 1.9 KB
<?php

namespace Lackoxygen\TiktokShop\Response;

use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Arr;
use Lackoxygen\TiktokShop\Util\Json;

class ResultSet implements Arrayable, \Countable
{
    /**
     * @var array|mixed
     */
    protected array $items = [];

    /**
     * @param array $items
     */
    public function __construct(array $items)
    {
        $this->items = $items;
    }

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

        return 10000 === $array['code'];
    }

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

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

    /**
     * @return array
     */
    public function getData(): array
    {
        $array = $this->toArray();

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

    /**
     * @param string $key
     * @param string $default
     * @return array|\ArrayAccess|mixed
     */
    public function get(string $key, string $default = '')
    {
        return Arr::get($this->getData(), $key, $default);
    }

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

    /**
     * @return false|string
     */
    public function toJson()
    {
        return Json::marshal($this->toArray());
    }

    /**
     * @return int
     */
    public function count(): int
    {
        return count($this->items);
    }

    /**
     * @param $name
     * @return $this|array|\ArrayAccess|mixed
     */
    public function __get($name)
    {
        if (!Arr::exists($this->items, $name)) {
            return $this->items;
        }
        $items = Arr::get($this->items, $name);

        if (is_array($items)) {
            return new static($items);
        }

        return $items;
    }
}