add AqlExpression

This commit is contained in:
evgen-d 2014-10-08 16:34:50 +04:00
parent be068d5039
commit 2502cc87e7
3 changed files with 101 additions and 2 deletions

40
AqlExpression.php Normal file
View File

@ -0,0 +1,40 @@
<?php
/**
* User: evgen-d
* Date: 08.10.14
* Time: 16:00
*/
namespace devgroup\arangodb;
use yii\base\Object;
class AqlExpression extends Object
{
/**
* @var string the AQL expression represented by this object
*/
public $expression;
/**
* Constructor.
* @param string $expression the AQL expression represented by this object
* @param array $config additional configurations for this object
*/
public function __construct($expression, $config = [])
{
$this->expression = $expression;
parent::__construct($config);
}
/**
* The PHP magic function converting an object into a string.
* @return string the AQL expression.
*/
public function __toString()
{
return $this->expression;
}
}

View File

@ -480,7 +480,7 @@ class Query extends Component implements QueryInterface
public function insert($collection, $columns, $params = [], $db = null)
{
$doc = Json::encode($columns);
$doc = Serializer::encode($columns);
$clauses = [
"INSERT $doc IN {$this->quoteCollectionName($collection)}",
@ -587,7 +587,7 @@ class Query extends Component implements QueryInterface
protected function buildUpdate($collection, $columns)
{
return 'UPDATE ' . $collection . ' WITH '
. (is_array($columns) ? Json::encode($columns) : $columns) . ' IN '
. Serializer::encode($columns) . ' IN '
. $this->quoteCollectionName($collection);
}

59
Serializer.php Normal file
View File

@ -0,0 +1,59 @@
<?php
/**
* User: evgen-d
* Date: 08.10.14
* Time: 16:04
*/
namespace devgroup\arangodb;
use yii\base\Arrayable;
class Serializer
{
public static function encode($value, $options = 0)
{
$expressions = [];
$value = static::processData($value, $expressions, uniqid());
$json = json_encode($value, $options);
return empty($expressions) ? $json : strtr($json, $expressions);
}
protected static function processData($data, &$expressions, $expPrefix)
{
if (is_object($data)) {
if ($data instanceof AqlExpression) {
$token = "!{[$expPrefix=" . count($expressions) . ']}!';
$expressions['"' . $token . '"'] = $data->expression;
return $token;
} elseif ($data instanceof \JsonSerializable) {
$data = $data->jsonSerialize();
} elseif ($data instanceof Arrayable) {
$data = $data->toArray();
} else {
$result = [];
foreach ($data as $name => $value) {
$result[$name] = $value;
}
$data = $result;
}
if ($data === []) {
return new \stdClass();
}
}
if (is_array($data)) {
foreach ($data as $key => $value) {
if (is_array($value) || is_object($value)) {
$data[$key] = static::processData($value, $expressions, $expPrefix);
}
}
}
return $data;
}
}