ResponseCastable.php
1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?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();
}
}
}