HashConditionBuilder.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. use yii\helpers\ArrayHelper;
  13. /**
  14. * Class HashConditionBuilder builds objects of [[HashCondition]]
  15. *
  16. * @author Dmytro Naumenko <d.naumenko.a@gmail.com>
  17. * @since 2.0.14
  18. */
  19. class HashConditionBuilder implements ExpressionBuilderInterface
  20. {
  21. use ExpressionBuilderTrait;
  22. /**
  23. * Method builds the raw SQL from the $expression that will not be additionally
  24. * escaped or quoted.
  25. *
  26. * @param ExpressionInterface|HashCondition $expression the expression to be built.
  27. * @param array $params the binding parameters.
  28. * @return string the raw SQL that will not be additionally escaped or quoted.
  29. */
  30. public function build(ExpressionInterface $expression, array &$params = [])
  31. {
  32. $hash = $expression->getHash();
  33. $parts = [];
  34. foreach ($hash as $column => $value) {
  35. if (ArrayHelper::isTraversable($value) || $value instanceof Query) {
  36. // IN condition
  37. $parts[] = $this->queryBuilder->buildCondition(new InCondition($column, 'IN', $value), $params);
  38. } else {
  39. if (strpos($column, '(') === false) {
  40. $column = $this->queryBuilder->db->quoteColumnName($column);
  41. }
  42. if ($value === null) {
  43. $parts[] = "$column IS NULL";
  44. } elseif ($value instanceof ExpressionInterface) {
  45. $parts[] = "$column=" . $this->queryBuilder->buildExpression($value, $params);
  46. } else {
  47. $phName = $this->queryBuilder->bindParam($value, $params);
  48. $parts[] = "$column=$phName";
  49. }
  50. }
  51. }
  52. return count($parts) === 1 ? $parts[0] : '(' . implode(') AND (', $parts) . ')';
  53. }
  54. }