| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentBooking\Framework\Database; |
| 4 |
|
| 5 |
use Throwable; |
| 6 |
use PDOException; |
| 7 |
|
| 8 |
class QueryException extends PDOException |
| 9 |
{ |
| 10 |
|
| 11 |
/** |
| 12 |
* The SQL for the query. |
| 13 |
* |
| 14 |
* @var string |
| 15 |
*/ |
| 16 |
protected $sql; |
| 17 |
|
| 18 |
/** |
| 19 |
* The bindings for the query. |
| 20 |
* |
| 21 |
* @var array |
| 22 |
*/ |
| 23 |
protected $bindings; |
| 24 |
|
| 25 |
/** |
| 26 |
* Create a new query exception instance. |
| 27 |
* |
| 28 |
* @param string $sql |
| 29 |
* @param array $bindings |
| 30 |
* @param \Throwable $previous |
| 31 |
* @return void |
| 32 |
*/ |
| 33 |
public function __construct($sql, array $bindings, Throwable $previous) |
| 34 |
{ |
| 35 |
parent::__construct('', 0, $previous); |
| 36 |
|
| 37 |
$this->sql = $sql; |
| 38 |
$this->bindings = $bindings; |
| 39 |
$this->code = $previous->getCode(); |
| 40 |
$this->message = $this->formatMessage($sql, $bindings, $previous); |
| 41 |
|
| 42 |
if ($previous instanceof PDOException) { |
| 43 |
$this->errorInfo = $previous->errorInfo; |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Format the SQL error message. |
| 49 |
* |
| 50 |
* @param string $sql |
| 51 |
* @param array $bindings |
| 52 |
* @param \Exception $previous |
| 53 |
* @return string |
| 54 |
*/ |
| 55 |
protected function formatMessage($sql, $bindings, $previous) |
| 56 |
{ |
| 57 |
$message = $this->strReplaceArray('\?', $bindings, $sql); |
| 58 |
|
| 59 |
return $previous->getMessage() . ' (SQL: ' . $message . ')'; |
| 60 |
} |
| 61 |
|
| 62 |
/** |
| 63 |
* Get the SQL for the query. |
| 64 |
* |
| 65 |
* @return string |
| 66 |
*/ |
| 67 |
public function getSql() |
| 68 |
{ |
| 69 |
return $this->sql; |
| 70 |
} |
| 71 |
|
| 72 |
/** |
| 73 |
* Get the bindings for the query. |
| 74 |
* |
| 75 |
* @return array |
| 76 |
*/ |
| 77 |
public function getBindings() |
| 78 |
{ |
| 79 |
return $this->bindings; |
| 80 |
} |
| 81 |
|
| 82 |
/** |
| 83 |
* Replace placeholders with bindings |
| 84 |
* |
| 85 |
* @param string $search |
| 86 |
* @param array $replace |
| 87 |
* @param string $subject |
| 88 |
* @return string $subject |
| 89 |
*/ |
| 90 |
protected function strReplaceArray($search, array $replace, $subject) |
| 91 |
{ |
| 92 |
foreach ($replace as $value) { |
| 93 |
$subject = preg_replace('/' . $search . '/', $value, $subject, 1); |
| 94 |
} |
| 95 |
|
| 96 |
return $subject; |
| 97 |
} |
| 98 |
} |
| 99 |
|