QueryExpression.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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. $typeMap = ($types instanceof TypeMap) ? $types : new TypeMap($types);
  62. $this->typeMap($typeMap);
  63. $this->type(strtoupper($conjunction));
  64. if (!empty($conditions)) {
  65. $this->add($conditions);
  66. }
  67. }
  68. /**
  69. * Changes the conjunction for the conditions at this level of the expression tree.
  70. * If called with no arguments it will return the currently configured value.
  71. *
  72. * @param string $conjunction value to be used for joining conditions. If null it
  73. * will not set any value, but return the currently stored one
  74. * @return string|QueryExpression
  75. */
  76. public function type($conjunction = null) {
  77. if ($conjunction === null) {
  78. return $this->_conjunction;
  79. }
  80. $this->_conjunction = strtoupper($conjunction);
  81. return $this;
  82. }
  83. /**
  84. * Adds one or more conditions to this expression object. Conditions can be
  85. * expressed in a one dimensional array, that will cause all conditions to
  86. * be added directly at this level of the tree or they can be nested arbitrarily
  87. * making it create more expression objects that will be nested inside and
  88. * configured to use the specified conjunction.
  89. *
  90. * If the type passed for any of the fields is expressed "type[]" (note braces)
  91. * then it will cause the placeholder to be re-written dynamically so if the
  92. * value is an array, it will create as many placeholders as values are in it.
  93. *
  94. * @param string|array|QueryExpression $conditions single or multiple conditions to
  95. * be added. When using and array and the key is 'OR' or 'AND' a new expression
  96. * object will be created with that conjunction and internal array value passed
  97. * as conditions.
  98. * @param array $types associative array of fields pointing to the type of the
  99. * values that are being passed. Used for correctly binding values to statements.
  100. * @see \Cake\Database\Query::where() for examples on conditions
  101. * @return QueryExpression
  102. */
  103. public function add($conditions, $types = []) {
  104. if (is_string($conditions)) {
  105. $this->_conditions[] = $conditions;
  106. return $this;
  107. }
  108. if ($conditions instanceof ExpressionInterface) {
  109. $this->_conditions[] = $conditions;
  110. return $this;
  111. }
  112. $this->_addConditions($conditions, $types);
  113. return $this;
  114. }
  115. /**
  116. * Adds a new condition to the expression object in the form "field = value".
  117. *
  118. * @param string $field database field to be compared against value
  119. * @param mixed $value the value to be bound to $field for comparison
  120. * @param string $type the type name for $value as configured using the Type map.
  121. * If it is suffixed with "[]" and the value is an array then multiple placeholders
  122. * will be created, one per each value in the array.
  123. * @return QueryExpression
  124. */
  125. public function eq($field, $value, $type = null) {
  126. return $this->add(new Comparison($field, $value, $type, '='));
  127. }
  128. /**
  129. * Adds a new condition to the expression object in the form "field != value".
  130. *
  131. * @param string $field database field to be compared against value
  132. * @param mixed $value the value to be bound to $field for comparison
  133. * @param string $type the type name for $value as configured using the Type map.
  134. * If it is suffixed with "[]" and the value is an array then multiple placeholders
  135. * will be created, one per each value in the array.
  136. * @return QueryExpression
  137. */
  138. public function notEq($field, $value, $type = null) {
  139. return $this->add(new Comparison($field, $value, $type, '!='));
  140. }
  141. /**
  142. * Adds a new condition to the expression object in the form "field > value".
  143. *
  144. * @param string $field database field to be compared against value
  145. * @param mixed $value the value to be bound to $field for comparison
  146. * @param string $type the type name for $value as configured using the Type map.
  147. * @return QueryExpression
  148. */
  149. public function gt($field, $value, $type = null) {
  150. return $this->add(new Comparison($field, $value, $type, '>'));
  151. }
  152. /**
  153. * Adds a new condition to the expression object in the form "field < value".
  154. *
  155. * @param string $field database field to be compared against value
  156. * @param mixed $value the value to be bound to $field for comparison
  157. * @param string $type the type name for $value as configured using the Type map.
  158. * @return QueryExpression
  159. */
  160. public function lt($field, $value, $type = null) {
  161. return $this->add(new Comparison($field, $value, $type, '<'));
  162. }
  163. /**
  164. * Adds a new condition to the expression object in the form "field >= value".
  165. *
  166. * @param string $field database field to be compared against value
  167. * @param mixed $value the value to be bound to $field for comparison
  168. * @param string $type the type name for $value as configured using the Type map.
  169. * @return QueryExpression
  170. */
  171. public function gte($field, $value, $type = null) {
  172. return $this->add(new Comparison($field, $value, $type, '>='));
  173. }
  174. /**
  175. * Adds a new condition to the expression object in the form "field <= value".
  176. *
  177. * @param string $field database field to be compared against value
  178. * @param mixed $value the value to be bound to $field for comparison
  179. * @param string $type the type name for $value as configured using the Type map.
  180. * @return QueryExpression
  181. */
  182. public function lte($field, $value, $type = null) {
  183. return $this->add(new Comparison($field, $value, $type, '<='));
  184. }
  185. /**
  186. * Adds a new condition to the expression object in the form "field IS NULL".
  187. *
  188. * @param string $field database field to be tested for null
  189. * @return QueryExpression
  190. */
  191. public function isNull($field) {
  192. return $this->add($field . ' IS NULL');
  193. }
  194. /**
  195. * Adds a new condition to the expression object in the form "field IS NOT NULL".
  196. *
  197. * @param string $field database field to be tested for not null
  198. * @return QueryExpression
  199. */
  200. public function isNotNull($field) {
  201. return $this->add($field . ' IS NOT NULL');
  202. }
  203. /**
  204. * Adds a new condition to the expression object in the form "field LIKE value".
  205. *
  206. * @param string $field database field to be compared against value
  207. * @param mixed $value the value to be bound to $field for comparison
  208. * @param string $type the type name for $value as configured using the Type map.
  209. * @return QueryExpression
  210. */
  211. public function like($field, $value, $type = null) {
  212. return $this->add(new Comparison($field, $value, $type, 'LIKE'));
  213. }
  214. /**
  215. * Adds a new condition to the expression object in the form "field NOT LIKE value".
  216. *
  217. * @param string $field database field to be compared against value
  218. * @param mixed $value the value to be bound to $field for comparison
  219. * @param string $type the type name for $value as configured using the Type map.
  220. * @return QueryExpression
  221. */
  222. public function notLike($field, $value, $type = null) {
  223. return $this->add(new Comparison($field, $value, $type, 'NOT LIKE'));
  224. }
  225. /**
  226. * Adds a new condition to the expression object in the form
  227. * "field IN (value1, value2)".
  228. *
  229. * @param string $field database field to be compared against value
  230. * @param array $values the value to be bound to $field for comparison
  231. * @param string $type the type name for $value as configured using the Type map.
  232. * @return QueryExpression
  233. */
  234. public function in($field, $values, $type = null) {
  235. $type = $type ?: 'string';
  236. $type .= '[]';
  237. $values = $values instanceof ExpressionInterface ? $values : (array)$values;
  238. return $this->add(new Comparison($field, $values, $type, 'IN'));
  239. }
  240. /**
  241. * Adds a new condition to the expression object in the form
  242. * "field NOT IN (value1, value2)".
  243. *
  244. * @param string $field database field to be compared against value
  245. * @param array $values the value to be bound to $field for comparison
  246. * @param string $type the type name for $value as configured using the Type map.
  247. * @return QueryExpression
  248. */
  249. public function notIn($field, $values, $type = null) {
  250. $type = $type ?: 'string';
  251. $type .= '[]';
  252. $values = $values instanceof ExpressionInterface ? $values : (array)$values;
  253. return $this->add(new Comparison($field, $values, $type, 'NOT IN'));
  254. }
  255. // @codingStandardsIgnoreStart
  256. /**
  257. * Returns a new QueryExpresion object containing all the conditions passed
  258. * and set up the conjunction to be "AND"
  259. *
  260. * @param string|array|QueryExpression $conditions to be joined with AND
  261. * @param array $types associative array of fields pointing to the type of the
  262. * values that are being passed. Used for correctly binding values to statements.
  263. * @return \Cake\Database\Expression\QueryExpression
  264. */
  265. public function and_($conditions, $types = []) {
  266. if (is_callable($conditions)) {
  267. return $conditions(new self([], $this->typeMap()->types($types)));
  268. }
  269. return new self($conditions, $this->typeMap()->types($types));
  270. }
  271. /**
  272. * Returns a new QueryExpresion object containing all the conditions passed
  273. * and set up the conjunction to be "OR"
  274. *
  275. * @param string|array|QueryExpression $conditions to be joined with OR
  276. * @param array $types associative array of fields pointing to the type of the
  277. * values that are being passed. Used for correctly binding values to statements.
  278. * @return \Cake\Database\Expression\QueryExpression
  279. */
  280. public function or_($conditions, $types = []) {
  281. if (is_callable($conditions)) {
  282. return $conditions(new self([], $this->typeMap()->types($types), 'OR'));
  283. }
  284. return new self($conditions, $this->typeMap()->types($types), 'OR');
  285. }
  286. // @codingStandardsIgnoreEnd
  287. /**
  288. * Adds a new set of conditions to this level of the tree and negates
  289. * the final result by prepending a NOT, it will look like
  290. * "NOT ( (condition1) AND (conditions2) )" conjunction depends on the one
  291. * currently configured for this object.
  292. *
  293. * @param string|array|QueryExpression $conditions to be added and negated
  294. * @param array $types associative array of fields pointing to the type of the
  295. * values that are being passed. Used for correctly binding values to statements.
  296. * @return QueryExpression
  297. */
  298. public function not($conditions, $types = []) {
  299. return $this->add(['NOT' => $conditions], $types);
  300. }
  301. /**
  302. * Returns the number of internal conditions that are stored in this expression.
  303. * Useful to determine if this expression object is void or it will generate
  304. * a non-empty string when compiled
  305. *
  306. * @return integer
  307. */
  308. public function count() {
  309. return count($this->_conditions);
  310. }
  311. /**
  312. * Returns the string representation of this object so that it can be used in a
  313. * SQL query. Note that values condition values are not included in the string,
  314. * in their place placeholders are put and can be replaced by the quoted values
  315. * accordingly.
  316. *
  317. * @param \Cake\Database\ValueBinder $generator Placeholder generator object
  318. * @return string
  319. */
  320. public function sql(ValueBinder $generator) {
  321. $conjunction = $this->_conjunction;
  322. $template = ($this->count() === 1) ? '%s' : '(%s)';
  323. $parts = [];
  324. foreach ($this->_conditions as $part) {
  325. if ($part instanceof ExpressionInterface) {
  326. $part = $part->sql($generator);
  327. }
  328. $parts[] = $part;
  329. }
  330. return sprintf($template, implode(" $conjunction ", $parts));
  331. }
  332. /**
  333. * Traverses the tree structure of this query expression by executing a callback
  334. * function for each of the conditions that are included in this object.
  335. * Useful for compiling the final expression, or doing
  336. * introspection in the structure.
  337. *
  338. * Callback function receives as only argument an instance of a QueryExpression
  339. *
  340. * @param callable $callable
  341. * @return void
  342. */
  343. public function traverse(callable $callable) {
  344. foreach ($this->_conditions as $c) {
  345. if ($c instanceof ExpressionInterface) {
  346. $callable($c);
  347. $c->traverse($callable);
  348. }
  349. }
  350. }
  351. /**
  352. * Executes a callable function for each of the parts that form this expression
  353. * Callable function is required to return a value, which will the one with
  354. * which the currently visited part will be replaced. If the callable function
  355. * returns null then the part will be discarded completely from this expression
  356. *
  357. * The callback function will receive each of the conditions as first param and
  358. * the key as second param. It is possible to declare the second parameter as
  359. * passed by reference, this will enable you to change the key under which the
  360. * modified part is stored.
  361. *
  362. * @param callable $callable
  363. * @return QueryExpression
  364. */
  365. public function iterateParts(callable $callable) {
  366. $parts = [];
  367. foreach ($this->_conditions as $k => $c) {
  368. $key =& $k;
  369. $part = $callable($c, $key);
  370. if ($part !== null) {
  371. $parts[$key] = $part;
  372. }
  373. }
  374. $this->_conditions = $parts;
  375. return $this;
  376. }
  377. /**
  378. * Auxiliary function used for decomposing a nested array of conditions and build
  379. * a tree structure inside this object to represent the full SQL expression.
  380. * String conditions are stored directly in the conditions, while any other
  381. * representation is wrapped around an adequate instance or of this class.
  382. *
  383. * @param array $conditions list of conditions to be stored in this object
  384. * @param array $types list of types associated on fields referenced in $conditions
  385. * @return void
  386. */
  387. protected function _addConditions(array $conditions, array $types) {
  388. $operators = ['and', 'or', 'xor'];
  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, $this->typeMap()->types($types), $numericKey ? 'AND' : $k);
  400. continue;
  401. }
  402. if (strtolower($k) === 'not') {
  403. $this->_conditions[] = new UnaryExpression(new self($c, $this->typeMap()->types($types)), [], '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, $types);
  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. * @param array $types List of types where the field can be found so the value
  426. * can be converted accordingly.
  427. * @return string|QueryExpression
  428. */
  429. protected function _parseCondition($field, $value, $types) {
  430. $operator = '=';
  431. $expression = $field;
  432. $parts = explode(' ', trim($field), 2);
  433. if (count($parts) > 1) {
  434. list($expression, $operator) = $parts;
  435. }
  436. if (!empty($types)) {
  437. $this->typeMap()->types($types);
  438. }
  439. $type = $this->typeMap()->type($expression);
  440. $multi = false;
  441. $typeMultiple = strpos($type, '[]') !== false;
  442. if (in_array(strtolower(trim($operator)), ['in', 'not in']) || $typeMultiple) {
  443. $type = $type ?: 'string';
  444. $type .= $typeMultiple ? null : '[]';
  445. $operator = $operator == '=' ? 'IN' : $operator;
  446. $operator = $operator == '!=' ? 'NOT IN' : $operator;
  447. $typeMultiple = true;
  448. }
  449. if ($typeMultiple) {
  450. $value = $value instanceof ExpressionInterface ? $value : (array)$value;
  451. }
  452. return new Comparison($expression, $value, $type, $operator);
  453. }
  454. /**
  455. * Returns an array of placeholders that will have a bound value corresponding
  456. * to each value in the first argument.
  457. *
  458. * @param string $field database field to be used to bind values
  459. * @param array $values
  460. * @param string $type the type to be used to bind the values
  461. * @return array
  462. */
  463. protected function _bindMultiplePlaceholders($field, $values, $type) {
  464. $type = str_replace('[]', '', $type);
  465. $params = [];
  466. foreach ($values as $value) {
  467. $params[] = $this->_bindValue($field, $value, $type);
  468. }
  469. return implode(', ', $params);
  470. }
  471. }