QueryExpression.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  14. */
  15. namespace Cake\Database\Expression;
  16. use Cake\Database\ExpressionInterface;
  17. use Cake\Database\Query;
  18. use Cake\Database\TypeMap;
  19. use Cake\Database\TypeMapTrait;
  20. use Cake\Database\ValueBinder;
  21. use \Countable;
  22. /**
  23. * Represents a SQL Query expression. Internally it stores a tree of
  24. * expressions that can be compiled by converting this object to string
  25. * and will contain a correctly parenthesized and nested expression.
  26. *
  27. */
  28. class QueryExpression implements ExpressionInterface, Countable {
  29. use TypeMapTrait;
  30. /**
  31. * String to be used for joining each of the internal expressions
  32. * this object internally stores for example "AND", "OR", etc.
  33. *
  34. * @var string
  35. */
  36. protected $_conjunction;
  37. /**
  38. * A list of strings or other expression objects that represent the "branches" of
  39. * the expression tree. For example one key of the array might look like "sum > :value"
  40. *
  41. * @var array
  42. */
  43. protected $_conditions = [];
  44. /**
  45. * Constructor. A new expression object can be created without any params and
  46. * be built dynamically. Otherwise it is possible to pass an array of conditions
  47. * containing either a tree-like array structure to be parsed and/or other
  48. * expression objects. Optionally, you can set the conjunction keyword to be used
  49. * for joining each part of this level of the expression tree.
  50. *
  51. * @param array $conditions tree-like array structure containing all the conditions
  52. * to be added or nested inside this expression object.
  53. * @param array|TypeMap $types associative array of types to be associated with the values
  54. * passed in $conditions.
  55. * @param string $conjunction the glue that will join all the string conditions at this
  56. * level of the expression tree. For example "AND", "OR", "XOR"...
  57. * @param TypeMap $typeMap contains default and call specific type mapping
  58. * @see QueryExpression::add() for more details on $conditions and $types
  59. */
  60. public function __construct($conditions = [], $types = [], $conjunction = 'AND') {
  61. $this->typeMap($types);
  62. $this->type(strtoupper($conjunction));
  63. if (!empty($conditions)) {
  64. $this->add($conditions, $this->typeMap()->types());
  65. }
  66. }
  67. /**
  68. * Changes the conjunction for the conditions at this level of the expression tree.
  69. * If called with no arguments it will return the currently configured value.
  70. *
  71. * @param string $conjunction value to be used for joining conditions. If null it
  72. * will not set any value, but return the currently stored one
  73. * @return string|QueryExpression
  74. */
  75. public function type($conjunction = null) {
  76. if ($conjunction === null) {
  77. return $this->_conjunction;
  78. }
  79. $this->_conjunction = strtoupper($conjunction);
  80. return $this;
  81. }
  82. /**
  83. * Adds one or more conditions to this expression object. Conditions can be
  84. * expressed in a one dimensional array, that will cause all conditions to
  85. * be added directly at this level of the tree or they can be nested arbitrarily
  86. * making it create more expression objects that will be nested inside and
  87. * configured to use the specified conjunction.
  88. *
  89. * If the type passed for any of the fields is expressed "type[]" (note braces)
  90. * then it will cause the placeholder to be re-written dynamically so if the
  91. * value is an array, it will create as many placeholders as values are in it.
  92. *
  93. * @param string|array|QueryExpression $conditions single or multiple conditions to
  94. * be added. When using and array and the key is 'OR' or 'AND' a new expression
  95. * object will be created with that conjunction and internal array value passed
  96. * as conditions.
  97. * @param array $types associative array of fields pointing to the type of the
  98. * values that are being passed. Used for correctly binding values to statements.
  99. * @see \Cake\Database\Query::where() for examples on conditions
  100. * @return QueryExpression
  101. */
  102. public function add($conditions, $types = []) {
  103. if (is_string($conditions)) {
  104. $this->_conditions[] = $conditions;
  105. return $this;
  106. }
  107. if ($conditions instanceof ExpressionInterface) {
  108. $this->_conditions[] = $conditions;
  109. return $this;
  110. }
  111. $this->_addConditions($conditions, $types);
  112. return $this;
  113. }
  114. /**
  115. * Adds a new condition to the expression object in the form "field = value".
  116. *
  117. * @param string $field database field to be compared against value
  118. * @param mixed $value the value to be bound to $field for comparison
  119. * @param string $type the type name for $value as configured using the Type map.
  120. * If it is suffixed with "[]" and the value is an array then multiple placeholders
  121. * will be created, one per each value in the array.
  122. * @return QueryExpression
  123. */
  124. public function eq($field, $value, $type = null) {
  125. return $this->add(new Comparison($field, $value, $type, '='));
  126. }
  127. /**
  128. * Adds a new condition to the expression object in the form "field != value".
  129. *
  130. * @param string $field database field to be compared against value
  131. * @param mixed $value the value to be bound to $field for comparison
  132. * @param string $type the type name for $value as configured using the Type map.
  133. * If it is suffixed with "[]" and the value is an array then multiple placeholders
  134. * will be created, one per each value in the array.
  135. * @return QueryExpression
  136. */
  137. public function notEq($field, $value, $type = null) {
  138. return $this->add(new Comparison($field, $value, $type, '!='));
  139. }
  140. /**
  141. * Adds a new condition to the expression object in the form "field > value".
  142. *
  143. * @param string $field database field to be compared against value
  144. * @param mixed $value the value to be bound to $field for comparison
  145. * @param string $type the type name for $value as configured using the Type map.
  146. * @return QueryExpression
  147. */
  148. public function gt($field, $value, $type = null) {
  149. return $this->add(new Comparison($field, $value, $type, '>'));
  150. }
  151. /**
  152. * Adds a new condition to the expression object in the form "field < value".
  153. *
  154. * @param string $field database field to be compared against value
  155. * @param mixed $value the value to be bound to $field for comparison
  156. * @param string $type the type name for $value as configured using the Type map.
  157. * @return QueryExpression
  158. */
  159. public function lt($field, $value, $type = null) {
  160. return $this->add(new Comparison($field, $value, $type, '<'));
  161. }
  162. /**
  163. * Adds a new condition to the expression object in the form "field >= value".
  164. *
  165. * @param string $field database field to be compared against value
  166. * @param mixed $value the value to be bound to $field for comparison
  167. * @param string $type the type name for $value as configured using the Type map.
  168. * @return QueryExpression
  169. */
  170. public function gte($field, $value, $type = null) {
  171. return $this->add(new Comparison($field, $value, $type, '>='));
  172. }
  173. /**
  174. * Adds a new condition to the expression object in the form "field <= value".
  175. *
  176. * @param string $field database field to be compared against value
  177. * @param mixed $value the value to be bound to $field for comparison
  178. * @param string $type the type name for $value as configured using the Type map.
  179. * @return QueryExpression
  180. */
  181. public function lte($field, $value, $type = null) {
  182. return $this->add(new Comparison($field, $value, $type, '<='));
  183. }
  184. /**
  185. * Adds a new condition to the expression object in the form "field IS NULL".
  186. *
  187. * @param string $field database field to be tested for null
  188. * @return QueryExpression
  189. */
  190. public function isNull($field) {
  191. return $this->add($field . ' IS NULL');
  192. }
  193. /**
  194. * Adds a new condition to the expression object in the form "field IS NOT NULL".
  195. *
  196. * @param string $field database field to be tested for not null
  197. * @return QueryExpression
  198. */
  199. public function isNotNull($field) {
  200. return $this->add($field . ' IS NOT NULL');
  201. }
  202. /**
  203. * Adds a new condition to the expression object in the form "field LIKE value".
  204. *
  205. * @param string $field database field to be compared against value
  206. * @param mixed $value the value to be bound to $field for comparison
  207. * @param string $type the type name for $value as configured using the Type map.
  208. * @return QueryExpression
  209. */
  210. public function like($field, $value, $type = null) {
  211. return $this->add(new Comparison($field, $value, $type, 'LIKE'));
  212. }
  213. /**
  214. * Adds a new condition to the expression object in the form "field NOT LIKE value".
  215. *
  216. * @param string $field database field to be compared against value
  217. * @param mixed $value the value to be bound to $field for comparison
  218. * @param string $type the type name for $value as configured using the Type map.
  219. * @return QueryExpression
  220. */
  221. public function notLike($field, $value, $type = null) {
  222. return $this->add(new Comparison($field, $value, $type, 'NOT LIKE'));
  223. }
  224. /**
  225. * Adds a new condition to the expression object in the form
  226. * "field IN (value1, value2)".
  227. *
  228. * @param string $field database field to be compared against value
  229. * @param array $values the value to be bound to $field for comparison
  230. * @param string $type the type name for $value as configured using the Type map.
  231. * @return QueryExpression
  232. */
  233. public function in($field, $values, $type = null) {
  234. $type = $type ?: 'string';
  235. $type .= '[]';
  236. $values = $values instanceof ExpressionInterface ? $values : (array)$values;
  237. return $this->add(new Comparison($field, $values, $type, 'IN'));
  238. }
  239. /**
  240. * Adds a new condition to the expression object in the form
  241. * "field NOT IN (value1, value2)".
  242. *
  243. * @param string $field database field to be compared against value
  244. * @param array $values the value to be bound to $field for comparison
  245. * @param string $type the type name for $value as configured using the Type map.
  246. * @return QueryExpression
  247. */
  248. public function notIn($field, $values, $type = null) {
  249. $type = $type ?: 'string';
  250. $type .= '[]';
  251. $values = $values instanceof ExpressionInterface ? $values : (array)$values;
  252. return $this->add(new Comparison($field, $values, $type, 'NOT IN'));
  253. }
  254. // @codingStandardsIgnoreStart
  255. /**
  256. * Returns a new QueryExpresion object containing all the conditions passed
  257. * and set up the conjunction to be "AND"
  258. *
  259. * @param string|array|QueryExpression $conditions to be joined with AND
  260. * @param array $types associative array of fields pointing to the type of the
  261. * values that are being passed. Used for correctly binding values to statements.
  262. * @return \Cake\Database\Expression\QueryExpression
  263. */
  264. public function and_($conditions, $types = []) {
  265. if (is_callable($conditions)) {
  266. return $conditions(new self([], $this->typeMap()->types($types)));
  267. }
  268. return new self($conditions, $this->typeMap()->types($types));
  269. }
  270. /**
  271. * Returns a new QueryExpresion object containing all the conditions passed
  272. * and set up the conjunction to be "OR"
  273. *
  274. * @param string|array|QueryExpression $conditions to be joined with OR
  275. * @param array $types associative array of fields pointing to the type of the
  276. * values that are being passed. Used for correctly binding values to statements.
  277. * @return \Cake\Database\Expression\QueryExpression
  278. */
  279. public function or_($conditions, $types = []) {
  280. if (is_callable($conditions)) {
  281. return $conditions(new self([], $this->typeMap()->types($types), 'OR'));
  282. }
  283. return new self($conditions, $this->typeMap()->types($types), 'OR');
  284. }
  285. // @codingStandardsIgnoreEnd
  286. /**
  287. * Adds a new set of conditions to this level of the tree and negates
  288. * the final result by prepending a NOT, it will look like
  289. * "NOT ( (condition1) AND (conditions2) )" conjunction depends on the one
  290. * currently configured for this object.
  291. *
  292. * @param string|array|QueryExpression $conditions to be added and negated
  293. * @param array $types associative array of fields pointing to the type of the
  294. * values that are being passed. Used for correctly binding values to statements.
  295. * @return QueryExpression
  296. */
  297. public function not($conditions, $types = []) {
  298. return $this->add(['NOT' => $conditions], $types);
  299. }
  300. /**
  301. * Returns the number of internal conditions that are stored in this expression.
  302. * Useful to determine if this expression object is void or it will generate
  303. * a non-empty string when compiled
  304. *
  305. * @return integer
  306. */
  307. public function count() {
  308. return count($this->_conditions);
  309. }
  310. /**
  311. * Returns the string representation of this object so that it can be used in a
  312. * SQL query. Note that values condition values are not included in the string,
  313. * in their place placeholders are put and can be replaced by the quoted values
  314. * accordingly.
  315. *
  316. * @param \Cake\Database\ValueBinder $generator Placeholder generator object
  317. * @return string
  318. */
  319. public function sql(ValueBinder $generator) {
  320. $conjunction = $this->_conjunction;
  321. $template = ($this->count() === 1) ? '%s' : '(%s)';
  322. $parts = [];
  323. foreach ($this->_conditions as $part) {
  324. if ($part instanceof ExpressionInterface) {
  325. $part = $part->sql($generator);
  326. }
  327. $parts[] = $part;
  328. }
  329. return sprintf($template, implode(" $conjunction ", $parts));
  330. }
  331. /**
  332. * Traverses the tree structure of this query expression by executing a callback
  333. * function for each of the conditions that are included in this object.
  334. * Useful for compiling the final expression, or doing
  335. * introspection in the structure.
  336. *
  337. * Callback function receives as only argument an instance of a QueryExpression
  338. *
  339. * @param callable $callable
  340. * @return void
  341. */
  342. public function traverse(callable $callable) {
  343. foreach ($this->_conditions as $c) {
  344. if ($c instanceof ExpressionInterface) {
  345. $callable($c);
  346. $c->traverse($callable);
  347. }
  348. }
  349. }
  350. /**
  351. * Executes a callable function for each of the parts that form this expression
  352. * Callable function is required to return a value, which will the one with
  353. * which the currently visited part will be replaced. If the callable function
  354. * returns null then the part will be discarded completely from this expression
  355. *
  356. * The callback function will receive each of the conditions as first param and
  357. * the key as second param. It is possible to declare the second parameter as
  358. * passed by reference, this will enable you to change the key under which the
  359. * modified part is stored.
  360. *
  361. * @param callable $callable
  362. * @return QueryExpression
  363. */
  364. public function iterateParts(callable $callable) {
  365. $parts = [];
  366. foreach ($this->_conditions as $k => $c) {
  367. $key =& $k;
  368. $part = $callable($c, $key);
  369. if ($part !== null) {
  370. $parts[$key] = $part;
  371. }
  372. }
  373. $this->_conditions = $parts;
  374. return $this;
  375. }
  376. /**
  377. * Auxiliary function used for decomposing a nested array of conditions and build
  378. * a tree structure inside this object to represent the full SQL expression.
  379. * String conditions are stored directly in the conditions, while any other
  380. * representation is wrapped around an adequate instance or of this class.
  381. *
  382. * @param array $conditions list of conditions to be stored in this object
  383. * @param array $types list of types associated on fields referenced in $conditions
  384. * @return void
  385. */
  386. protected function _addConditions(array $conditions, array $types) {
  387. $operators = ['and', 'or', 'xor'];
  388. $typeMap = $this->typeMap()->types($types);
  389. foreach ($conditions as $k => $c) {
  390. $numericKey = is_numeric($k);
  391. if ($numericKey && empty($c)) {
  392. continue;
  393. }
  394. if ($numericKey && is_string($c)) {
  395. $this->_conditions[] = $c;
  396. continue;
  397. }
  398. if ($numericKey && is_array($c) || in_array(strtolower($k), $operators)) {
  399. $this->_conditions[] = new self($c, $typeMap, $numericKey ? 'AND' : $k);
  400. continue;
  401. }
  402. if (strtolower($k) === 'not') {
  403. $this->_conditions[] = new UnaryExpression(new self($c, $typeMap), [], 'NOT');
  404. continue;
  405. }
  406. if ($c instanceof self && count($c) > 0) {
  407. $this->_conditions[] = $c;
  408. continue;
  409. }
  410. if (!$numericKey) {
  411. $this->_conditions[] = $this->_parseCondition($k, $c);
  412. }
  413. }
  414. }
  415. /**
  416. * Parses a string conditions by trying to extract the operator inside it if any
  417. * and finally returning either an adequate QueryExpression object or a plain
  418. * string representation of the condition. This function is responsible for
  419. * generating the placeholders and replacing the values by them, while storing
  420. * the value elsewhere for future binding.
  421. *
  422. * @param string $field The value from with the actual field and operator will
  423. * be extracted.
  424. * @param mixed $value The value to be bound to a placeholder for the field
  425. * @return string|QueryExpression
  426. */
  427. protected function _parseCondition($field, $value) {
  428. $operator = '=';
  429. $expression = $field;
  430. $parts = explode(' ', trim($field), 2);
  431. if (count($parts) > 1) {
  432. list($expression, $operator) = $parts;
  433. }
  434. $type = $this->typeMap()->type($expression);
  435. $multi = false;
  436. $typeMultiple = strpos($type, '[]') !== false;
  437. if (in_array(strtolower(trim($operator)), ['in', 'not in']) || $typeMultiple) {
  438. $type = $type ?: 'string';
  439. $type .= $typeMultiple ? null : '[]';
  440. $operator = $operator == '=' ? 'IN' : $operator;
  441. $operator = $operator == '!=' ? 'NOT IN' : $operator;
  442. $typeMultiple = true;
  443. }
  444. if ($typeMultiple) {
  445. $value = $value instanceof ExpressionInterface ? $value : (array)$value;
  446. }
  447. return new Comparison($expression, $value, $type, $operator);
  448. }
  449. /**
  450. * Returns an array of placeholders that will have a bound value corresponding
  451. * to each value in the first argument.
  452. *
  453. * @param string $field database field to be used to bind values
  454. * @param array $values
  455. * @param string $type the type to be used to bind the values
  456. * @return array
  457. */
  458. protected function _bindMultiplePlaceholders($field, $values, $type) {
  459. $type = str_replace('[]', '', $type);
  460. $params = [];
  461. foreach ($values as $value) {
  462. $params[] = $this->_bindValue($field, $value, $type);
  463. }
  464. return implode(', ', $params);
  465. }
  466. }