Passed
Push — master ( ddb678...e2f2ed )
by Peter
02:37
created

Exception::customMessage()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 10
nc 2
nop 5
dl 0
loc 15
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AbterPhp\Framework\Databases\Migrations;
6
7
use Throwable;
8
9
class Exception extends \RuntimeException
10
{
11
    /**
12
     * Exception constructor.
13
     *
14
     * @param string[]       $errorInfo
15
     * @param string         $query
16
     * @param string|null    $className
17
     * @param string         $fileName
18
     * @param string         $message
19
     * @param int            $code
20
     * @param Throwable|null $previous
21
     */
22
    public function __construct(
23
        array $errorInfo,
24
        string $query,
25
        ?string $className = null,
26
        ?string $fileName = null,
27
        string $message = "",
28
        int $code = 0,
29
        Throwable $previous = null
30
    ) {
31
        if (array_diff(array_keys($errorInfo), [0, 1, 2])) {
32
            throw new \RuntimeException(sprintf('Invalid errorInfo received for constructing %s.', __CLASS__));
33
        }
34
35
        $message = $this->customMessage($errorInfo, $query, $className, $fileName, $message);
36
37
        parent::__construct($message, $code, $previous);
38
    }
39
40
    /**
41
     * @param string[]    $errorInfo
42
     * @param string      $query
43
     * @param string|null $className
44
     * @param string      $fileName
45
     * @param string      $message
46
     *
47
     * @return string
48
     */
49
    private function customMessage($errorInfo, $query, $className, $fileName, $message): string
50
    {
51
        $pieces   = [];
52
        $pieces[] = sprintf('Class: %s', $className ?: '(missing)');
53
        $pieces[] = sprintf('File: %s', $fileName ?: '(missing)');
54
        $pieces[] = sprintf('Query: %s', $query);
55
        if ($message) {
56
            $pieces[] = sprintf('Original message: %s', $message);
57
        }
58
59
        $pieces[] = sprintf('SqlState error code: %s', $errorInfo[0]);
60
        $pieces[] = sprintf('Driver error code: %s', $errorInfo[1]);
61
        $pieces[] = sprintf('Driver error message: %s', $errorInfo[2]);
62
63
        return join("\n", $pieces);
64
    }
65
}
66