Skip to content

Commit

Permalink
FIX: ensure limits to SQLQuery are passed as positive values
Browse files Browse the repository at this point in the history
  • Loading branch information
wilr committed Jun 29, 2012
1 parent 1686636 commit 4ee709e
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
16 changes: 14 additions & 2 deletions model/SQLQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -423,17 +423,29 @@ public function getLimit() {
*
* @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),
Expand Down
26 changes: 25 additions & 1 deletion tests/model/SQLQueryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,31 @@ function testSelectWithOrderbyClause() {

$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');
Expand Down

0 comments on commit 4ee709e

Please sign in to comment.