Skip to content

Commit

Permalink
added Dibi\Expression [Closes #264]
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Sep 21, 2017
1 parent 832313b commit 499e3ae
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
34 changes: 34 additions & 0 deletions src/Dibi/Expression.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

/**
* This file is part of the "dibi" - smart database abstraction layer.
* Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/

declare(strict_types=1);

namespace Dibi;


/**
* SQL expression.
*/
class Expression
{
use Strict;

/** @var array */
private $values;


public function __construct(...$values)
{
$this->values = $values;
}


public function getValues(): array
{
return $this->values;
}
}
3 changes: 3 additions & 0 deletions src/Dibi/Translator.php
Original file line number Diff line number Diff line change
Expand Up @@ -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**";
Expand Down
18 changes: 17 additions & 1 deletion tests/dibi/Translator.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
])
);

Expand All @@ -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 = [
Expand Down

0 comments on commit 499e3ae

Please sign in to comment.