packages/ztd-query-core/tests/Fake/FakeValueRenderer.php
1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Fake;
6
7use ZtdQuery\Platform\ValueRenderer;
8use ZtdQuery\Schema\ColumnDeclaration;
9use ZtdQuery\Schema\ColumnTypeFamily;
10
11/**
12 * A value renderer that writes SQL in the plainest form every dialect accepts.
13 *
14 * Real dialects disagree about how a boolean, a null and a quoted string are
15 * written, which is the whole reason this is an interface. A test about what
16 * the contract promises rather than about a dialect uses this.
17 */
18final class FakeValueRenderer implements ValueRenderer
19{
20 /**
21 * Writes a value as the SQL expression standing for it.
22 *
23 * @param mixed $value Value to write
24 * @param ColumnDeclaration|null $type Column type it is being written for, where one is known
25 *
26 * @return string The expression
27 */
28 public function renderValue(mixed $value, ?ColumnDeclaration $type = null): string
29 {
30 if ($value === null) {
31 return 'NULL';
32 }
33 if (is_bool($value)) {
34 return $value ? 'TRUE' : 'FALSE';
35 }
36 if (is_int($value) || is_float($value)) {
37 return $type?->family === ColumnTypeFamily::TEXT
38 ? "'" . (string) $value . "'"
39 : (string) $value;
40 }
41
42 return "'" . str_replace("'", "''", is_string($value) ? $value : '') . "'";
43 }
44}
45