LinodeException   A
last analyzed

Complexity

Total Complexity 2

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 2
eloc 8
dl 0
loc 31
c 1
b 0
f 0
rs 10
ccs 8
cts 8
cp 1

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A getErrors() 0 3 1
1
<?php
2
3
// ---------------------------------------------------------------------
4
//
5
//  Copyright (C) 2018-2024 Artem Rodygin
6
//
7
//  You should have received a copy of the MIT License along with
8
//  this file. If not, see <https://opensource.org/licenses/MIT>.
9
//
10
// ---------------------------------------------------------------------
11
12
namespace Linode\Exception;
13
14
use Psr\Http\Message\ResponseInterface;
15
16
/**
17
 * This type of exception is raised on every failed request and contains list of errors.
18
 *
19
 * Within each error object, the `field` parameter will be included if the error pertains to
20
 * a specific field in the JSON you’ve submitted. This will be omitted if there is no relevant
21
 * field. The `reason` is a human-readable explanation of the error, and will always be included.
22
 *
23
 * The exception code is an HTTP status code of the request. The exception message is a `reason`
24
 * of the first error object.
25
 */
26
class LinodeException extends \Exception
27
{
28
    /**
29
     * @var Error[] List of errors associated with the exception.
30
     */
31
    protected array $errors;
32
33
    /**
34
     * @param ResponseInterface $response Failed response.
35
     * @param null|\Throwable   $previous The previous throwable used for the exception chaining.
36
     */
37 2
    public function __construct(ResponseInterface $response, \Throwable $previous = null)
38
    {
39 2
        $code = $response->getStatusCode();
40 2
        $json = json_decode($response->getBody()->getContents() ?? '', true);
41
42 2
        $errors = $json['errors'] ?? [['reason' => 'Unknown error']];
43
44 2
        $this->errors = array_map(static fn ($error) => new Error($error['reason'], $error['field'] ?? null), $errors);
45
46 2
        parent::__construct($this->errors[0]->reason, $code, $previous);
47
    }
48
49
    /**
50
     * Returns list of errors associated with the exception.
51
     *
52
     * @return Error[]
53
     */
54 2
    public function getErrors(): array
55
    {
56 2
        return $this->errors;
57
    }
58
}
59