Response.php 1.5 KB
<?php

namespace Lackoxygen\TopWarehouse;

use Illuminate\Support\Arr;
use Lackoxygen\TopWarehouse\Constants\ResponseCode;
use Lackoxygen\TopWarehouse\Contracts\ResponseInterface;
use Lackoxygen\TopWarehouse\Exception\Exception;
use Lackoxygen\TopWarehouse\Utils\JsonUtil;
use Psr\Http\Message\ResponseInterface as PsrResponseInterface;

class Response implements ResponseInterface
{
    /**
     * @var PsrResponseInterface
     */
    protected $response;

    /**
     * Response constructor.
     *
     * @param PsrResponseInterface $response
     */
    public function __construct(PsrResponseInterface $response)
    {
        $this->response = $response;
    }

    /**
     * @inheritDoc
     */
    public function getStatusCode(): int
    {
        return $this->response->getStatusCode();
    }

    /**
     * @inheritDoc
     */
    public function isSuccess(): bool
    {
        if (200 !== $this->getStatusCode()) {
            return false;
        }

        $body = $this->toArray();

        return (int)Arr::get($body, 'status', 0) == ResponseCode::STATUS_SUCCESS;
    }

    /**
     * @inheritDoc
     */
    public function getContents(): string
    {
        return $this->response->getBody()->getContents();
    }

    /**
     * @inheritDoc
     */
    public function toArray(): array
    {
        return (array)JsonUtil::decode($this->getContents());
    }

    /**
     * @inheritDoc
     */
    public function __toString()
    {
        return $this->getContents();
    }
}