Skip to content
This repository
Browse code

FIX: ensure limits to SQLQuery are passed as positive values

  • Loading branch information...
commit 4ee709e88d004f34972385f8e2b7e4c3352d1d92 1 parent 1686636
Will Rossiter authored June 29, 2012
16  model/SQLQuery.php
@@ -423,17 +423,29 @@ public function getLimit() {
423 423
 	 *
424 424
 	 * @param int|string|array $limit If passed as a string or array, assumes SQL escaped data.
425 425
 	 * @param int $offset
  426
+	 *
  427
+	 * @throws InvalidArgumentException
  428
+	 *
426 429
 	 * @return SQLQuery This instance
427 430
 	 */
428 431
 	public function setLimit($limit, $offset = 0) {
  432
+		if((is_numeric($limit) && $limit < 0) || (is_numeric($offset) && $offset < 0)) {
  433
+			throw new InvalidArgumentException("SQLQuery::setLimit() only takes positive values");
  434
+		}
  435
+
429 436
 		if($limit && is_numeric($limit)) {
430 437
 			$this->limit = array(
431 438
 				'start' => $offset,
432 439
 				'limit' => $limit,
433 440
 			);
434 441
 		} else if($limit && is_string($limit)) {
435  
-			if(strpos($limit, ',') !== false) list($start, $innerLimit) = explode(',', $limit, 2);
436  
-			else list($innerLimit, $start) = explode(' OFFSET ', strtoupper($limit), 2);
  442
+			if(strpos($limit, ',') !== false) {
  443
+				list($start, $innerLimit) = explode(',', $limit, 2);
  444
+			}
  445
+			else {
  446
+				list($innerLimit, $start) = explode(' OFFSET ', strtoupper($limit), 2);
  447
+			}
  448
+
437 449
 			$this->limit = array(
438 450
 				'start' => trim($start),
439 451
 				'limit' => trim($innerLimit),
26  tests/model/SQLQueryTest.php
@@ -128,7 +128,31 @@ function testSelectWithOrderbyClause() {
128 128
 		
129 129
 		$this->assertEquals('SELECT *, RAND() AS "_SortColumn0" FROM MyTable ORDER BY "_SortColumn0" ASC', $query->sql());
130 130
 	}
131  
-	
  131
+
  132
+	/**
  133
+	 * @expectedException InvalidArgumentException
  134
+	 */
  135
+	public function testNegativeLimit() {
  136
+		$query = new SQLQuery();
  137
+		$query->setLimit(-10);
  138
+	}
  139
+
  140
+	/**
  141
+	 * @expectedException InvalidArgumentException
  142
+	 */
  143
+	public function testNegativeOffset() {
  144
+		$query = new SQLQuery();
  145
+		$query->setLimit(1, -10);
  146
+	}
  147
+
  148
+	/**
  149
+	 * @expectedException InvalidArgumentException
  150
+	 */
  151
+	public function testNegativeOffsetAndLimit() {
  152
+		$query = new SQLQuery();
  153
+		$query->setLimit(-10, -10);
  154
+	}
  155
+
132 156
 	public function testReverseOrderBy() {
133 157
 		$query = new SQLQuery();
134 158
 		$query->setFrom('MyTable');

0 notes on commit 4ee709e

Please sign in to comment.
Something went wrong with that request. Please try again.