Completed
Push — master ( 18d42b...fed0be )
by Rasmus
03:18
created

SQLException::emulatedPrepare()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 12
ccs 7
cts 7
cp 1
rs 9.2
cc 4
eloc 7
nc 5
nop 2
crap 4
1
<?php
2
3
namespace mindplay\sql\exceptions;
4
5
use Exception;
6
use RuntimeException;
7
8
/**
9
 * This Exception-type represents an SQL error
10
 */
11
class SQLException extends RuntimeException
12
{
13
    /**
14
     * @param string         $sql    SQL statement (with ":name" placeholders)
15
     * @param array          $params map of parameter name/value pairs (to bind against placeholders in the statement)
16
     * @param string         $message
17
     * @param int            $code
18
     * @param Exception|null $previous
19
     */
20 1
    public function __construct($sql, $params = [], $message = 'SQL Error', $code = 0, Exception $previous = null)
21
    {
22 1
        parent::__construct("{$message}\n" . $this->emulatedPrepare($sql, $params), $code, $previous);
23 1
    }
24
    
25
    /**
26
     * @param string $sql
27
     * @param array  $params
28
     *
29
     * @return string SQL with emulated prepare (for diagnostic purposes only)
30
     */
31 1
    private function emulatedPrepare($sql, array $params)
32
    {
33 1
        foreach ($params as $name => $value) {
34 1
            $quoted_value = $value === null
35 1
                ? "NULL"
36 1
                : (is_numeric($value) ? $value : "'{$value}'");
37
38 1
            $sql = str_replace(":{$name}", $quoted_value, $sql);
39
        }
40
41 1
        return $sql;
42
    }
43
}
44