Passed
Push — main ( 7064c3...9debc3 )
by BRUNO
02:38
created

DatabaseException   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
dl 0
loc 53
rs 10
c 1
b 0
f 0
wmc 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getParameters() 0 3 1
A getContextInfo() 0 8 1
A __construct() 0 18 5
A getQuery() 0 3 1
A getOriginalCode() 0 4 2
1
<?php
2
3
namespace BMorais\Database\Exception;
4
5
use Exception;
6
use Throwable;
7
8
/**
9
 * Custom Database Exception
10
 *
11
 * @author Bruno Morais <[email protected]>
12
 * @copyright MIT, bmorais.com
13
 * @package bmorais\database
14
 */
15
class DatabaseException extends Exception
16
{
17
    private ?string $query;
18
    private ?array $parameters;
19
20
    public function __construct(
21
        string $message,
22
        int|string $code = 0,  // ✅ Aceita int ou string
23
        ?Throwable $previous = null,
24
        ?string $query = null,
25
        ?array $parameters = null
26
    ) {
27
        // ✅ Converte string para int de forma segura
28
        $intCode = is_string($code) ? (int)$code : $code;
29
        if ($intCode === 0 && is_string($code) && !empty($code)) {
30
            // Se a conversão resultou em 0 mas o código original não era vazio,
31
            // usa um código padrão
32
            $intCode = 1000;
33
        }
34
35
        parent::__construct($message, $intCode, $previous);
36
        $this->query = $query;
37
        $this->parameters = $parameters;
38
    }
39
40
    public function getQuery(): ?string
41
    {
42
        return $this->query;
43
    }
44
45
    public function getParameters(): ?array
46
    {
47
        return $this->parameters;
48
    }
49
50
    public function getContextInfo(): array
51
    {
52
        return [
53
            'message' => $this->getMessage(),
54
            'query' => $this->query,
55
            'parameters' => $this->parameters,
56
            'file' => $this->getFile(),
57
            'line' => $this->getLine()
58
        ];
59
    }
60
61
    /**
62
     * Get original PDO error code (may be string)
63
     */
64
    public function getOriginalCode(): int|string
65
    {
66
        $previous = $this->getPrevious();
67
        return $previous ? $previous->getCode() : $this->getCode();
0 ignored issues
show
introduced by
$previous is of type Exception, thus it always evaluated to true.
Loading history...
68
    }
69
}