Code Coverage |
||||||||||
Classes and Traits |
Functions and Methods |
Lines |
||||||||
Total | |
100.00% |
1 / 1 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
26 / 26 |
SqlDumper | |
100.00% |
1 / 1 |
|
100.00% |
2 / 2 |
12 | |
100.00% |
26 / 26 |
dump | |
100.00% |
1 / 1 |
11 | |
100.00% |
4 / 4 |
|||
anonymous function | |
100.00% |
1 / 1 |
1 | |
100.00% |
2 / 2 |
<?php | |
namespace Puyo\Db; | |
/** | |
* 生でPDOを使うプロジェクト用のSQL dumper | |
*/ | |
class SqlDumper | |
{ | |
/** | |
* 実行するPrepared Statementを non-prepared なSQLにして返す | |
* @param string $psql (non) prepared statement sql | |
* @param array $params placeholders | |
* @return string binded sql | |
*/ | |
public static function dump($psql, $params) | |
{ | |
$keys = []; | |
$values = []; | |
$isNamedPlaceholders = false; | |
if (is_array($params) && !empty($params) && is_string(key($params))) { | |
uksort($params, function ($k1, $k2) { | |
return strlen($k2) - strlen($k1); | |
}); | |
$isNamedPlaceholders = true; | |
} | |
foreach ($params as $key => $value) { | |
if (is_string($key)) { | |
$keys[] = '/:' . ltrim($key, ':') . '/'; | |
} else { | |
$keys[] = '/[?]/'; | |
} | |
if (is_string($value)) { | |
$values[] = "'" . addslashes($value) . "'"; | |
} elseif (is_int($value)) { | |
$values[] = strval($value); | |
} elseif (is_float($value)) { | |
$values[] = strval($value); | |
} elseif (is_null($value)) { | |
$values[] = 'null'; | |
} | |
} | |
if ($isNamedPlaceholders) { | |
return preg_replace($keys, $values, $psql); | |
} else { | |
return preg_replace($keys, $values, $psql, 1, $count); | |
} | |
} | |
} |