JsonExpressionBuilder.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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\pgsql;
  8. use yii\db\ArrayExpression;
  9. use yii\db\ExpressionBuilderInterface;
  10. use yii\db\ExpressionBuilderTrait;
  11. use yii\db\ExpressionInterface;
  12. use yii\db\JsonExpression;
  13. use yii\db\Query;
  14. use yii\helpers\Json;
  15. /**
  16. * Class JsonExpressionBuilder builds [[JsonExpression]] for PostgreSQL DBMS.
  17. *
  18. * @author Dmytro Naumenko <d.naumenko.a@gmail.com>
  19. * @since 2.0.14
  20. */
  21. class JsonExpressionBuilder implements ExpressionBuilderInterface
  22. {
  23. use ExpressionBuilderTrait;
  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)" . $this->getTypecast($expression);
  34. }
  35. if ($value instanceof ArrayExpression) {
  36. $placeholder = 'array_to_json(' . $this->queryBuilder->buildExpression($value, $params) . ')';
  37. } else {
  38. $placeholder = $this->queryBuilder->bindParam(Json::encode($value), $params);
  39. }
  40. return $placeholder . $this->getTypecast($expression);
  41. }
  42. /**
  43. * @param JsonExpression $expression
  44. * @return string the typecast expression based on [[type]].
  45. */
  46. protected function getTypecast(JsonExpression $expression)
  47. {
  48. if ($expression->getType() === null) {
  49. return '';
  50. }
  51. return '::' . $expression->getType();
  52. }
  53. }