LikeCondition.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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\base\InvalidArgumentException;
  9. /**
  10. * Class LikeCondition represents a `LIKE` condition.
  11. *
  12. * @author Dmytro Naumenko <d.naumenko.a@gmail.com>
  13. * @since 2.0.14
  14. */
  15. class LikeCondition extends SimpleCondition
  16. {
  17. /**
  18. * @var array|false map of chars to their replacements, false if characters should not be escaped
  19. * or either null or empty array if escaping is condition builder responsibility.
  20. * By default it's set to `null`.
  21. */
  22. protected $escapingReplacements;
  23. /**
  24. * @param string $column the column name.
  25. * @param string $operator the operator to use (e.g. `LIKE`, `NOT LIKE`, `OR LIKE` or `OR NOT LIKE`)
  26. * @param string[]|string $value single value or an array of values that $column should be compared with.
  27. * If it is an empty array the generated expression will be a `false` value if operator is `LIKE` or `OR LIKE`
  28. * and empty if operator is `NOT LIKE` or `OR NOT LIKE`.
  29. */
  30. public function __construct($column, $operator, $value)
  31. {
  32. parent::__construct($column, $operator, $value);
  33. }
  34. /**
  35. * This method allows to specify how to escape special characters in the value(s).
  36. *
  37. * @param array an array of mappings from the special characters to their escaped counterparts.
  38. * You may use `false` or an empty array to indicate the values are already escaped and no escape
  39. * should be applied. Note that when using an escape mapping (or the third operand is not provided),
  40. * the values will be automatically enclosed within a pair of percentage characters.
  41. */
  42. public function setEscapingReplacements($escapingReplacements)
  43. {
  44. $this->escapingReplacements = $escapingReplacements;
  45. }
  46. /**
  47. * @return array|false
  48. */
  49. public function getEscapingReplacements()
  50. {
  51. return $this->escapingReplacements;
  52. }
  53. /**
  54. * {@inheritdoc}
  55. * @throws InvalidArgumentException if wrong number of operands have been given.
  56. */
  57. public static function fromArrayDefinition($operator, $operands)
  58. {
  59. if (!isset($operands[0], $operands[1])) {
  60. throw new InvalidArgumentException("Operator '$operator' requires two operands.");
  61. }
  62. $condition = new static($operands[0], $operator, $operands[1]);
  63. if (isset($operands[2])) {
  64. $condition->escapingReplacements = $operands[2];
  65. }
  66. return $condition;
  67. }
  68. }