LimitExpression.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\DB\Sql;
  7. /**
  8. * Class LimitExpression
  9. */
  10. class LimitExpression extends Expression
  11. {
  12. /**
  13. * @var string
  14. */
  15. protected $sql;
  16. /**
  17. * @var int
  18. */
  19. protected $count;
  20. /**
  21. * @var int
  22. */
  23. protected $offset;
  24. /**
  25. * @param string $sql
  26. * @param int $count
  27. * @param int $offset
  28. */
  29. public function __construct(
  30. $sql,
  31. $count,
  32. $offset = 0
  33. ) {
  34. $this->sql = $sql;
  35. $this->count = $count;
  36. $this->offset = $offset;
  37. }
  38. /**
  39. * @inheritdoc
  40. */
  41. public function __toString()
  42. {
  43. $sql = $this->sql;
  44. $count = (int)$this->count;
  45. if ($count <= 0) {
  46. /** @see Zend_Db_Adapter_Exception */
  47. #require_once 'Zend/Db/Adapter/Exception.php';
  48. throw new \Zend_Db_Adapter_Exception("LIMIT argument count=$count is not valid");
  49. }
  50. $offset = (int)$this->offset;
  51. if ($offset < 0) {
  52. /** @see Zend_Db_Adapter_Exception */
  53. #require_once 'Zend/Db/Adapter/Exception.php';
  54. throw new \Zend_Db_Adapter_Exception("LIMIT argument offset=$offset is not valid");
  55. }
  56. $sql .= " LIMIT $count";
  57. if ($offset > 0) {
  58. $sql .= " OFFSET $offset";
  59. }
  60. return trim($sql);
  61. }
  62. }