From 4ee709e88d004f34972385f8e2b7e4c3352d1d92 Mon Sep 17 00:00:00 2001 From: Will Rossiter Date: Fri, 29 Jun 2012 19:40:28 +1200 Subject: [PATCH] FIX: ensure limits to SQLQuery are passed as positive values --- model/SQLQuery.php | 16 ++++++++++++++-- tests/model/SQLQueryTest.php | 26 +++++++++++++++++++++++++- 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/model/SQLQuery.php b/model/SQLQuery.php index daf9e0ad0..55f934473 100644 --- a/model/SQLQuery.php +++ b/model/SQLQuery.php @@ -423,17 +423,29 @@ class SQLQuery { * * @param int|string|array $limit If passed as a string or array, assumes SQL escaped data. * @param int $offset + * + * @throws InvalidArgumentException + * * @return SQLQuery This instance */ public function setLimit($limit, $offset = 0) { + if((is_numeric($limit) && $limit < 0) || (is_numeric($offset) && $offset < 0)) { + throw new InvalidArgumentException("SQLQuery::setLimit() only takes positive values"); + } + if($limit && is_numeric($limit)) { $this->limit = array( 'start' => $offset, 'limit' => $limit, ); } else if($limit && is_string($limit)) { - if(strpos($limit, ',') !== false) list($start, $innerLimit) = explode(',', $limit, 2); - else list($innerLimit, $start) = explode(' OFFSET ', strtoupper($limit), 2); + if(strpos($limit, ',') !== false) { + list($start, $innerLimit) = explode(',', $limit, 2); + } + else { + list($innerLimit, $start) = explode(' OFFSET ', strtoupper($limit), 2); + } + $this->limit = array( 'start' => trim($start), 'limit' => trim($innerLimit), diff --git a/tests/model/SQLQueryTest.php b/tests/model/SQLQueryTest.php index 3819b352c..64402400f 100755 --- a/tests/model/SQLQueryTest.php +++ b/tests/model/SQLQueryTest.php @@ -128,7 +128,31 @@ class SQLQueryTest extends SapphireTest { $this->assertEquals('SELECT *, RAND() AS "_SortColumn0" FROM MyTable ORDER BY "_SortColumn0" ASC', $query->sql()); } - + + /** + * @expectedException InvalidArgumentException + */ + public function testNegativeLimit() { + $query = new SQLQuery(); + $query->setLimit(-10); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testNegativeOffset() { + $query = new SQLQuery(); + $query->setLimit(1, -10); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testNegativeOffsetAndLimit() { + $query = new SQLQuery(); + $query->setLimit(-10, -10); + } + public function testReverseOrderBy() { $query = new SQLQuery(); $query->setFrom('MyTable');