ResponseCastable.php 1.65 KB
<?php
/**
 * Created by PhpStorm.
 * User: ChuXiang
 * Date: 2019/8/14
 * Time: 11:17
 */

namespace PgServiceSdk\Kernel\Traits;


use PgServiceSdk\Kernel\Contracts\ResponseFormatted;
use PgServiceSdk\Kernel\Exceptions\InvalidConfigException;
use PgServiceSdk\Kernel\Http\Response;
use Psr\Http\Message\ResponseInterface;

trait ResponseCastable
{
    /**
     * 将响应转化为响应格式
     *
     * @param ResponseInterface $response
     * @param null $type
     * @return \Psr\Http\Message\ResponseInterface|\PgServiceSdk\Kernel\Support\Collection|array|object|string
     *
     * @throws InvalidConfigException
     */
    protected function costResponseToType(ResponseInterface $response, $type = null)
    {
        $guzzleResponse = Response::buildFromPsrResponse($response);
        $guzzleResponse->getBody()->rewind();

        switch ($type ? $type : 'array') {
            case 'collection':
                return $guzzleResponse->toCollection();
                break;
            case 'array':
                return $guzzleResponse->toArray();
                break;
            case 'object':
                return $guzzleResponse->toObject();
                break;
            case 'raw':
                return $guzzleResponse;
                break;
            default :
                if (!is_subclass_of($type, ResponseFormatted::class)) {
                    throw new InvalidConfigException(sprintf(
                        'Config key "response_type" classname must be an instanceof %s',
                         ResponseFormatted::class
                    ));
                }

                return (new $type($response))->format();
        }
    }
}