XsollaAPIException::fromBadResponse()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2.004

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 9
cts 10
cp 0.9
rs 9.7666
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2.004
1
<?php
2
3
namespace Xsolla\SDK\Exception\API;
4
5
use GuzzleHttp\Exception\BadResponseException;
6
use Xsolla\SDK\Exception\XsollaException;
7
8
class XsollaAPIException extends XsollaException
9
{
10
    protected static $exceptions = [
11
        422 => '\Xsolla\SDK\Exception\API\UnprocessableEntityException',
12
        403 => '\Xsolla\SDK\Exception\API\AccessDeniedException',
13
    ];
14
15
    protected static $messageTemplate =
16
<<<'EOF'
17
Xsolla API Error Response:
18
19
Previous Exception:
20
===================
21
%s
22
23
Request:
24
===================
25
%s
26
27
Response:
28
===================
29
%s
30
EOF;
31
32
    /**
33
     * @param  BadResponseException $previous
34
     * @return XsollaAPIException
35
     */
36 1
    public static function fromBadResponse(BadResponseException $previous)
37
    {
38 1
        $statusCode = $previous->getResponse()->getStatusCode();
39 1
        $message = sprintf(
40 1
            static::$messageTemplate,
41 1
            $previous->getMessage(),
42 1
            \GuzzleHttp\Psr7\str($previous->getRequest()),
43 1
            \GuzzleHttp\Psr7\str($previous->getResponse())
0 ignored issues
show
Bug introduced by
It seems like $previous->getResponse() can be null; however, GuzzleHttp\Psr7\str() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
44
        );
45 1
        if (array_key_exists($statusCode, static::$exceptions)) {
46 1
            return new static::$exceptions[$statusCode]($message, 0, $previous);
47
        }
48
49
        return new self($message, 0, $previous);
50
    }
51
}
52