BetweenColumnsConditionBuilder.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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\conditions;
  8. use yii\db\ExpressionBuilderInterface;
  9. use yii\db\ExpressionBuilderTrait;
  10. use yii\db\ExpressionInterface;
  11. use yii\db\Query;
  12. /**
  13. * Class BetweenColumnsConditionBuilder builds objects of [[BetweenColumnsCondition]]
  14. *
  15. * @author Dmytro Naumenko <d.naumenko.a@gmail.com>
  16. * @since 2.0.14
  17. */
  18. class BetweenColumnsConditionBuilder implements ExpressionBuilderInterface
  19. {
  20. use ExpressionBuilderTrait;
  21. /**
  22. * Method builds the raw SQL from the $expression that will not be additionally
  23. * escaped or quoted.
  24. *
  25. * @param ExpressionInterface|BetweenColumnsCondition $expression the expression to be built.
  26. * @param array $params the binding parameters.
  27. * @return string the raw SQL that will not be additionally escaped or quoted.
  28. */
  29. public function build(ExpressionInterface $expression, array &$params = [])
  30. {
  31. $operator = $expression->getOperator();
  32. $startColumn = $this->escapeColumnName($expression->getIntervalStartColumn(), $params);
  33. $endColumn = $this->escapeColumnName($expression->getIntervalEndColumn(), $params);
  34. $value = $this->createPlaceholder($expression->getValue(), $params);
  35. return "$value $operator $startColumn AND $endColumn";
  36. }
  37. /**
  38. * Prepares column name to be used in SQL statement.
  39. *
  40. * @param Query|ExpressionInterface|string $columnName
  41. * @param array $params the binding parameters.
  42. * @return string
  43. */
  44. protected function escapeColumnName($columnName, &$params = [])
  45. {
  46. if ($columnName instanceof Query) {
  47. list($sql, $params) = $this->queryBuilder->build($columnName, $params);
  48. return "($sql)";
  49. } elseif ($columnName instanceof ExpressionInterface) {
  50. return $this->queryBuilder->buildExpression($columnName, $params);
  51. } elseif (strpos($columnName, '(') === false) {
  52. return $this->queryBuilder->db->quoteColumnName($columnName);
  53. }
  54. return $columnName;
  55. }
  56. /**
  57. * Attaches $value to $params array and returns placeholder.
  58. *
  59. * @param mixed $value
  60. * @param array $params passed by reference
  61. * @return string
  62. */
  63. protected function createPlaceholder($value, &$params)
  64. {
  65. if ($value instanceof ExpressionInterface) {
  66. return $this->queryBuilder->buildExpression($value, $params);
  67. }
  68. return $this->queryBuilder->bindParam($value, $params);
  69. }
  70. }