OrderByExpression.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 3.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Database\Expression;
  17. use Cake\Database\ExpressionInterface;
  18. use Cake\Database\ValueBinder;
  19. /**
  20. * An expression object for ORDER BY clauses
  21. */
  22. class OrderByExpression extends QueryExpression
  23. {
  24. /**
  25. * Constructor
  26. *
  27. * @param string|array|\Cake\Database\ExpressionInterface $conditions The sort columns
  28. * @param array|\Cake\Database\TypeMap $types The types for each column.
  29. * @param string $conjunction The glue used to join conditions together.
  30. */
  31. public function __construct($conditions = [], $types = [], $conjunction = '')
  32. {
  33. parent::__construct($conditions, $types, $conjunction);
  34. }
  35. /**
  36. * Convert the expression into a SQL fragment.
  37. *
  38. * @param \Cake\Database\ValueBinder $generator Placeholder generator object
  39. * @return string
  40. */
  41. public function sql(ValueBinder $generator)
  42. {
  43. $order = [];
  44. foreach ($this->_conditions as $k => $direction) {
  45. if ($direction instanceof ExpressionInterface) {
  46. $direction = $direction->sql($generator);
  47. }
  48. $order[] = is_numeric($k) ? $direction : sprintf('%s %s', $k, $direction);
  49. }
  50. return sprintf('ORDER BY %s', implode(', ', $order));
  51. }
  52. /**
  53. * Auxiliary function used for decomposing a nested array of conditions and
  54. * building a tree structure inside this object to represent the full SQL expression.
  55. *
  56. * New order by expressions are merged to existing ones
  57. *
  58. * @param array $orders list of order by expressions
  59. * @param array $types list of types associated on fields referenced in $conditions
  60. * @return void
  61. */
  62. protected function _addConditions(array $orders, array $types)
  63. {
  64. $this->_conditions = array_merge($this->_conditions, $orders);
  65. }
  66. }