Code Coverage |
||||||||||
Classes and Traits |
Functions and Methods |
Lines |
||||||||
Total | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
CRAP | |
100.00% |
22 / 22 |
SqlDumper | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
11 | |
100.00% |
22 / 22 |
dump | |
100.00% |
1 / 1 |
11 | |
100.00% |
22 / 22 |
<?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); | |
} | |
} | |
} |