DatabaseException   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 6
eloc 20
c 4
b 0
f 0
dl 0
loc 37
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 26 5
A getSqlState() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace WebServCo\Framework\Exceptions;
6
7
final class DatabaseException extends ApplicationException
8
{
9
    public const CODE = 0;
10
11
    protected string $sqlState = '';
12
13
    public function __construct(string $message, ?\Throwable $previous = null)
14
    {
15
        $code = self::CODE;
16
17
        switch (true) {
18
            case $previous instanceof \PDOException:
19
                if (!empty($previous->errorInfo[1])) {
20
                    $code = $previous->errorInfo[1];
21
                    $this->sqlState = $previous->errorInfo[0];
22
                }
23
24
                if (!empty($previous->errorInfo[2])) {
25
                    // cleaner error message without all the codes.
26
                    $message = $previous->errorInfo[2];
27
                }
28
                break;
29
            case $previous instanceof self:
30
                // A \PDOException that was re-thrown
31
                $code = $previous->getCode();
32
                $this->sqlState = $previous->getSqlState();
33
                break;
34
            default:
35
                break;
36
        }
37
38
        parent::__construct($message, $code, $previous);
39
    }
40
41
    public function getSqlState(): string
42
    {
43
        return $this->sqlState;
44
    }
45
}
46