JsonExpressionBuilder.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\db\mysql;
  8. use yii\db\ExpressionBuilderInterface;
  9. use yii\db\ExpressionBuilderTrait;
  10. use yii\db\ExpressionInterface;
  11. use yii\db\JsonExpression;
  12. use yii\db\Query;
  13. use yii\helpers\Json;
  14. /**
  15. * Class JsonExpressionBuilder builds [[JsonExpression]] for MySQL DBMS.
  16. *
  17. * @author Dmytro Naumenko <d.naumenko.a@gmail.com>
  18. * @since 2.0.14
  19. */
  20. class JsonExpressionBuilder implements ExpressionBuilderInterface
  21. {
  22. use ExpressionBuilderTrait;
  23. const PARAM_PREFIX = ':qp';
  24. /**
  25. * {@inheritdoc}
  26. * @param JsonExpression|ExpressionInterface $expression the expression to be built
  27. */
  28. public function build(ExpressionInterface $expression, array &$params = [])
  29. {
  30. $value = $expression->getValue();
  31. if ($value instanceof Query) {
  32. list ($sql, $params) = $this->queryBuilder->build($value, $params);
  33. return "($sql)";
  34. }
  35. $placeholder = static::PARAM_PREFIX . count($params);
  36. $params[$placeholder] = Json::encode($value);
  37. return "CAST($placeholder AS JSON)";
  38. }
  39. }