OrderClauseExpression.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Database\Expression;
  16. use Cake\Database\ExpressionInterface;
  17. use Cake\Database\ValueBinder;
  18. /**
  19. * An expression object for complex ORDER BY clauses
  20. */
  21. class OrderClauseExpression implements ExpressionInterface, FieldInterface
  22. {
  23. use FieldTrait;
  24. /**
  25. * The direction of sorting.
  26. *
  27. * @var string
  28. */
  29. protected $_direction;
  30. /**
  31. * Constructor
  32. *
  33. * @param \Cake\Database\ExpressionInterface|string $field The field to order on.
  34. * @param string $direction The direction to sort on.
  35. */
  36. public function __construct($field, $direction)
  37. {
  38. $this->_field = $field;
  39. $this->_direction = strtolower($direction) === 'asc' ? 'ASC' : 'DESC';
  40. }
  41. /**
  42. * {@inheritDoc}
  43. */
  44. public function sql(ValueBinder $generator)
  45. {
  46. $field = $this->_field;
  47. if ($field instanceof ExpressionInterface) {
  48. $field = $field->sql($generator);
  49. }
  50. return sprintf('%s %s', $field, $this->_direction);
  51. }
  52. /**
  53. * {@inheritDoc}
  54. */
  55. public function traverse(callable $visitor)
  56. {
  57. if ($this->_field instanceof ExpressionInterface) {
  58. $visitor($this->_field);
  59. $this->_field->traverse($visitor);
  60. }
  61. }
  62. /**
  63. * Create a deep clone of the order clause.
  64. *
  65. * @return void
  66. */
  67. public function __clone()
  68. {
  69. if ($this->_field instanceof ExpressionInterface) {
  70. $this->_field = clone $this->_field;
  71. }
  72. }
  73. }