| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace ClickHouseDB\Quote; |
||
| 6 | |||
| 7 | use ClickHouseDB\Exception\UnsupportedValueType; |
||
| 8 | use ClickHouseDB\Query\Expression\Expression; |
||
| 9 | use ClickHouseDB\Type\Type; |
||
| 10 | use DateTimeInterface; |
||
| 11 | use function addslashes; |
||
|
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
| 12 | use function is_bool; |
||
| 13 | use function is_callable; |
||
| 14 | use function is_float; |
||
| 15 | use function is_int; |
||
| 16 | use function is_object; |
||
| 17 | use function is_string; |
||
| 18 | use function sprintf; |
||
| 19 | |||
| 20 | class ValueFormatter |
||
| 21 | { |
||
| 22 | /** |
||
| 23 | * @param mixed $value |
||
|
0 ignored issues
–
show
|
|||
| 24 | * @param bool $addQuotes |
||
|
0 ignored issues
–
show
|
|||
| 25 | * @return mixed |
||
| 26 | */ |
||
| 27 | 36 | public static function formatValue($value, bool $addQuotes = true) |
|
| 28 | { |
||
| 29 | 36 | if ($value instanceof DateTimeInterface) { |
|
| 30 | 2 | $value = $value->format('Y-m-d H:i:s'); |
|
| 31 | } |
||
| 32 | |||
| 33 | 36 | if (is_float($value) || is_int($value) || is_bool($value) || $value === null) { |
|
| 34 | 21 | return $value; |
|
| 35 | } |
||
| 36 | |||
| 37 | 31 | if ($value instanceof Type) { |
|
| 38 | 1 | return $value->getValue(); |
|
| 39 | } |
||
| 40 | |||
| 41 | 31 | if ($value instanceof Expression) { |
|
| 42 | 1 | return $value->getValue(); |
|
| 43 | } |
||
| 44 | |||
| 45 | 30 | if (is_object($value) && is_callable([$value, '__toString'])) { |
|
| 46 | 1 | $value = (string) $value; |
|
| 47 | } |
||
| 48 | |||
| 49 | 30 | if (is_string($value)) { |
|
| 50 | 29 | if ($addQuotes) { |
|
| 51 | 19 | return self::formatStringParameter(self::escapeString($value)); |
|
| 52 | } |
||
| 53 | |||
| 54 | 10 | return $value; |
|
| 55 | } |
||
| 56 | |||
| 57 | 1 | throw UnsupportedValueType::new($value); |
|
| 58 | } |
||
| 59 | |||
| 60 | /** |
||
| 61 | * Escape an string |
||
| 62 | * |
||
| 63 | * @param string $value |
||
|
0 ignored issues
–
show
|
|||
| 64 | * @return string |
||
| 65 | */ |
||
| 66 | 19 | private static function escapeString($value) |
|
|
0 ignored issues
–
show
|
|||
| 67 | { |
||
| 68 | 19 | return addslashes($value); |
|
| 69 | } |
||
| 70 | |||
| 71 | /** |
||
| 72 | * @return string |
||
| 73 | */ |
||
| 74 | 19 | private static function formatStringParameter($value) |
|
|
0 ignored issues
–
show
|
|||
| 75 | { |
||
| 76 | 19 | return sprintf("'%s'", $value); |
|
| 77 | } |
||
| 78 | } |
||
| 79 |