Passed
Branch simplistic (3d6a47)
by Ali
02:39
created

Handler::handleException()   A

Complexity

Conditions 6
Paths 4

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 16
c 1
b 0
f 0
nc 4
nop 7
dl 0
loc 23
rs 9.1111
1
<?php
2
3
/*
4
 * Part of the Saudi Address API PHP package.
5
 *
6
 * NOTICE OF LICENSE
7
 *
8
 * Licensed under the MIT.
9
 *
10
 * This source file is subject to the MIT License that is
11
 * bundled with this package in the LICENSE file.
12
 *
13
 * @package    Saudi Address
14
 * @version    2.0
15
 * @author     Ali Alharthi
16
 * @license    MIT
17
 * @copyright  (c) 2020, Ali Alharthi
18
 * @link       https://aalharthi.sa
19
 */
20
21
namespace AliAlharthi\SaudiAddress\Exception;
22
23
use GuzzleHttp\Exception\ClientException;
24
25
class Handler
26
{
27
    /**
28
     * List of mapped exceptions and their corresponding status codes.
29
     *
30
     * @var array
31
     */
32
    protected $exceptionsByStatusCode = [
33
34
        // Often missing a required parameter
35
        400 => 'BadRequest',
36
37
        // Invalid Saudi National Address API key provided
38
        401 => 'Unauthorized',
39
40
        // Invalid Saudi National Address API key provided
41
        401 => 'Unauthorized',
42
43
        // Reached Saudi National Address API account rate limit
44
        403 => 'ApiLimitExceeded',
45
46
        // Parameters were valid but request failed
47
        402 => 'InvalidRequest',
48
49
        // The requested item doesn't exist
50
        404 => 'NotFound',
51
52
        // Something went wrong on Saudi National Address's end
53
        500 => 'ServerError',
54
        502 => 'ServerError',
55
        503 => 'ServerError',
56
        504 => 'ServerError',
57
58
    ];
59
60
    /**
61
     * Constructor.
62
     *
63
     * @param   \GuzzleHttp\Exception\ClientException  $exception
64
     * @throws  \AliAlharthi\SaudiAddress\Exception\SaudiAddressException
65
     */
66
    public function __construct(ClientException $exception)
67
    {
68
        $response = $exception->getResponse();
69
70
        $headers = $response->getHeaders();
71
72
        $statusCode = $response->getStatusCode();
73
74
        $rawOutput = json_decode($response->getBody(true), true);
0 ignored issues
show
Unused Code introduced by
The call to Psr\Http\Message\MessageInterface::getBody() has too many arguments starting with true. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

74
        $rawOutput = json_decode($response->/** @scrutinizer ignore-call */ getBody(true), true);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
75
76
        $error = isset($rawOutput['error']) ? $rawOutput['error'] : [];
77
78
        $errorCode = isset($error['code']) ? $error['code'] : null;
79
80
        $errorType = isset($error['type']) ? $error['type'] : null;
81
82
        $message = isset($error['message']) ? $error['message'] : null;
83
84
        $missingParameter = isset($error['param']) ? $error['param'] : null;
85
86
        $this->handleException(
87
            $message,
88
            $headers,
89
            $statusCode,
90
            $errorType,
91
            $errorCode,
92
            $missingParameter,
93
            $rawOutput
94
        );
95
    }
96
97
    /**
98
     * Guesses the FQN of the exception to be thrown.
99
     *
100
     * @param   string  $message
101
     * @param   int     $statusCode
102
     * @param   string  $errorType
103
     * @param   string  $errorCode
104
     * @param   string  $missingParameter
105
     * @return  void
106
     * @throws  \AliAlharthi\SaudiAddress\Exception\SaudiAddressException
107
     */
108
    protected function handleException($message, $headers, $statusCode, $errorType, $errorCode, $missingParameter, $rawOutput)
109
    {
110
        if ($statusCode === 400 && $errorCode === 'rate_limit') {
111
            $class = 'ApiLimitExceeded';
112
        } elseif ($statusCode === 400 && $errorType === 'invalid_request_error') {
113
            $class = 'MissingParameter';
114
        } elseif (array_key_exists($statusCode, $this->exceptionsByStatusCode)) {
115
            $class = $this->exceptionsByStatusCode[$statusCode];
116
        } else {
117
            $class = 'SaudiAddress';
118
        }
119
120
        $class = "\\AliAlharthi\\SaudiAddress\\Exception\\{$class}Exception";
121
122
        $instance = new $class($message, $statusCode);
123
124
        $instance->setHeaders($headers);
125
        $instance->setErrorCode($errorCode);
126
        $instance->setErrorType($errorType);
127
        $instance->setMissingParameter($missingParameter);
128
        $instance->setRawOutput($rawOutput);
129
130
        throw $instance;
131
    }
132
}
133