ResultSet.php 2.6 KB
<?php

namespace Lackoxygen\TiktokShop\Response;

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

class ResultSet implements Arrayable, \Countable, \ArrayAccess
{
    /**
     * @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;
    }

    /**
     * @param $offset
     * @return void
     */
    public function offsetUnset($offset)
    {
        unset($this->items[$offset]);
    }

    /**
     * @param $offset
     * @param $value
     * @return void
     */
    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->items[] = $value;
        } else {
            $this->items[$offset] = $value;
        }
    }

    /**
     * @param $offset
     * @return mixed
     */
    public function offsetGet($offset)
    {
        return $this->items[$offset];
    }

    /**
     * @param $offset
     * @return bool
     */
    public function offsetExists($offset): bool
    {
        return isset($this->items, $offset);
    }
}