ResponseCastable::castResponseToType()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 11
c 2
b 0
f 0
dl 0
loc 16
rs 9.6111
cc 5
nc 5
nop 2
1
<?php
2
3
/*
4
 * This file is part of the overtrue/http.
5
 *
6
 * (c) overtrue <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Overtrue\Http\Traits;
13
14
use Overtrue\Http\Exceptions\InvalidArgumentException;
15
use Overtrue\Http\Responses\Response;
16
use Overtrue\Http\Support\Collection;
17
use Psr\Http\Message\ResponseInterface;
18
19
/**
20
 * Trait ResponseCastable.
21
 *
22
 * @author overtrue <[email protected]>
23
 */
24
trait ResponseCastable
25
{
26
    /**
27
     * @param \Psr\Http\Message\ResponseInterface $response
28
     * @param string|null                         $type
29
     *
30
     * @return array|\Overtrue\Http\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
31
     */
32
    protected function castResponseToType(ResponseInterface $response, $type = null)
33
    {
34
        if ('raw' === $type) {
35
            return $response;
36
        }
37
38
        $response = Response::buildFromPsrResponse($response);
39
        $response->getBody()->rewind();
40
41
        switch ($type ?? 'array') {
42
            case 'collection':
43
                return $response->toCollection();
44
            case 'array':
45
                return $response->toArray();
46
            case 'object':
47
                return $response->toObject();
48
        }
49
    }
50
51
    /**
52
     * @param mixed       $response
53
     * @param string|null $type
54
     *
55
     * @throws \Overtrue\Http\Exceptions\InvalidArgumentException
56
     *
57
     * @return array|\Overtrue\Http\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
58
     */
59
    protected function detectAndCastResponseToType($response, $type = null)
60
    {
61
        switch (true) {
62
            case $response instanceof ResponseInterface:
63
                $response = Response::buildFromPsrResponse($response);
64
65
                break;
66
            case ($response instanceof Collection) || is_array($response) || is_object($response):
67
                $response = new Response(200, [], json_encode($response));
68
69
                break;
70
            case is_scalar($response):
71
                $response = new Response(200, [], $response);
72
73
                break;
74
            default:
75
                throw new InvalidArgumentException(sprintf('Unsupported response type "%s"', gettype($response)));
76
        }
77
78
        return $this->castResponseToType($response, $type);
79
    }
80
}
81