Passed
Pull Request — master (#662)
by Songda
06:50
created

ArrayParser::query()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
c 0
b 0
f 0
dl 0
loc 11
rs 10
cc 2
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yansongda\Pay\Parser;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Yansongda\Pay\Contract\ParserInterface;
9
use Yansongda\Pay\Exception\Exception;
10
use Yansongda\Pay\Exception\InvalidResponseException;
11
use Yansongda\Supports\Str;
12
13
class ArrayParser implements ParserInterface
14
{
15
    /**
16
     * @throws \Yansongda\Pay\Exception\InvalidResponseException
17
     */
18
    public function parse(?ResponseInterface $response): array
19
    {
20
        if (is_null($response)) {
21
            throw new InvalidResponseException(Exception::RESPONSE_NONE);
22
        }
23
24
        $body = (string) $response->getBody();
25
26
        if (Str::contains($body, '&')) {
27
            return $this->query($body);
28
        }
29
30
        $result = json_decode($body, true);
31
32
        if (JSON_ERROR_NONE !== json_last_error()) {
33
            throw new InvalidResponseException(Exception::UNPACK_RESPONSE_ERROR, 'Unpack Response Error', ['body' => $body, 'response' => $response]);
34
        }
35
36
        return $result;
37
    }
38
39
    protected function query(string $body): array
40
    {
41
        $result = [];
42
43
        foreach (explode('&', $body) as $item) {
44
            $pos = strpos($item, '=');
45
46
            $result[substr($item, 0, $pos)] = substr($item, $pos + 1);
47
        }
48
49
        return $result;
50
    }
51
}
52