Issues (14)

src/Exception/Api/AbstractApiException.php (2 issues)

Labels
Severity
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Blackmine\Exception\Api;
6
7
use Blackmine\Client\Response\ApiResponse;
8
use Error;
9
use Exception;
10
use Throwable;
11
12
abstract class AbstractApiException extends Exception
13
{
14
    /**
15
     * @param string $message
16
     * @param int $code
17
     * @param Throwable|null $previous
18
     */
19
    public function __construct($message = "", $code = 0, ?Throwable $previous = null)
20
    {
21
        $message = $message === "" ? $this->getErrorMessage() : $message;
22
        $code = $code === 0 ? $this->getErrorCode() : $code;
23
24
        parent::__construct($message, $code, $previous);
25
    }
26
27
    /**
28
     * @return int
29
     */
30
    public function getErrorCode(): int
31
    {
32
        if (defined('static::ERROR_CODE')) {
33
            return static::ERROR_CODE;
0 ignored issues
show
The constant Blackmine\Exception\Api\...piException::ERROR_CODE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
34
        }
35
36
        throw new Error('Mandatory constant ERROR_CODE not defined in class: ' . get_class($this));
37
    }
38
39
    /**
40
     * @return string
41
     */
42
    public function getErrorMessage(): string
43
    {
44
        if (defined('static::ERROR_MESSAGE')) {
45
            return static::ERROR_MESSAGE;
0 ignored issues
show
The constant Blackmine\Exception\Api\...xception::ERROR_MESSAGE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
46
        }
47
48
        throw new Error('Mandatory constant ERROR_MESSAGE not defined in class: ' . get_class($this));
49
    }
50
51
    public static function fromApiResponse(
52
        ApiResponse $api_response,
53
        ?Throwable $previous = null
54
    ): AbstractApiException | Error {
55
        return match ($api_response->getStatus()) {
56
            401 => new UnauthorizedApiException(previous: $previous),
57
            403 => new InaccessibleResourceException(previous: $previous),
58
            404 => new EntityNotFoundException(previous: $previous),
59
            422 => new MalformedPayloadException(previous: $previous, errors: $api_response->getData()),
60
            default => new Error(message: "Undefined error", code: 1000, previous: $previous),
61
        };
62
    }
63
}
64