From 499e3aea40f13e044252644e7f8fd09391b1ef71 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Thu, 21 Sep 2017 14:51:31 +0200 Subject: [PATCH] added Dibi\Expression [Closes #264] --- src/Dibi/Expression.php | 34 ++++++++++++++++++++++++++++++++++ src/Dibi/Translator.php | 3 +++ tests/dibi/Translator.phpt | 18 +++++++++++++++++- 3 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 src/Dibi/Expression.php diff --git a/src/Dibi/Expression.php b/src/Dibi/Expression.php new file mode 100644 index 000000000..30b5b918a --- /dev/null +++ b/src/Dibi/Expression.php @@ -0,0 +1,34 @@ +values = $values; + } + + + public function getValues(): array + { + return $this->values; + } +} diff --git a/src/Dibi/Translator.php b/src/Dibi/Translator.php index e62bf80b4..63f9578e7 100644 --- a/src/Dibi/Translator.php +++ b/src/Dibi/Translator.php @@ -450,6 +450,9 @@ public function formatValue($value, ?string $modifier): string } elseif ($value instanceof Literal) { return (string) $value; + } elseif ($value instanceof Expression) { + return $this->connection->translate(...$value->getValues()); + } else { $type = is_object($value) ? get_class($value) : gettype($value); return $this->errors[] = "**Unexpected $type**"; diff --git a/tests/dibi/Translator.phpt b/tests/dibi/Translator.phpt index b4a34e2f7..9f49fd29f 100644 --- a/tests/dibi/Translator.phpt +++ b/tests/dibi/Translator.phpt @@ -478,7 +478,7 @@ Assert::same( 'title' => ['SHA1(%s)', 'Test product'], ], [ 'product_id' => 1, - 'title' => ['SHA1(%s)', 'Test product'], + 'title' => new Dibi\Expression('SHA1(%s)', 'Test product'), ]) ); @@ -490,6 +490,22 @@ Assert::same( ]) ); +Assert::same( + reformat('UPDATE [products] [product_id]=1, [title]=SHA1(\'Test product\')'), + $conn->translate('UPDATE [products]', [ + 'product_id' => 1, + 'title' => new Dibi\Expression('SHA1(%s)', 'Test product'), + ]) +); + +Assert::same( + reformat('SELECT * FROM [products] WHERE [product_id]=1, [title]=SHA1(\'Test product\')'), + $conn->translate('SELECT * FROM [products] WHERE', [ + 'product_id' => 1, + 'title' => new Dibi\Expression('SHA1(%s)', 'Test product'), + ]) +); + $e = Assert::exception(function () use ($conn) { $array6 = [