Skip to content

Commit

Permalink
added getFirstResult and getLastResult
Browse files Browse the repository at this point in the history
  • Loading branch information
Mauro Cassani committed Nov 15, 2017
1 parent c84bd85 commit 87df9bc
Showing 3 changed files with 69 additions and 0 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -87,6 +87,12 @@ $qb->addCriterion('company.name', 'Romaguera-Jacobson');
foreach ($qb->getResults() as $element){
// ...
}

// get first result
$first = $qb->getFirstResult();

// get last result
$last = $qb->getLastResult();
```

### Avaliable criteria operators
31 changes: 31 additions & 0 deletions src/QueryBuilder.php
Original file line number Diff line number Diff line change
@@ -177,6 +177,14 @@ public function limit($offset, $length)
return $this;
}

/**
* @param $array
* @param $arrayName
* @param $parentKey
* @param $foreignKey
*
* @return $this
*/
public function join($array, $arrayName, $parentKey, $foreignKey)
{
$this->join[] = [
@@ -199,8 +207,27 @@ public function getResults()
return array_map([$this, 'castElementToArray'], $results);
}

/**
* @return array
*/
public function getFirstResult()
{
return $this->getResults()[0] ?: [];
}

/**
* @return array
*/
public function getLastResult()
{
$count = count($this->getResults());

return $this->getResults()[$count-1] ?: [];
}

/**
* @param array $array
*
* @return array
*/
private function applySortingFilter(array $array)
@@ -210,13 +237,17 @@ private function applySortingFilter(array $array)

/**
* @param array $array
*
* @return array
*/
private function applyLimitFilter(array $array)
{
return LimitFilter::filter($array, $this->limit);
}

/**
* @return array
*/
private function applyJoinFilter()
{
return JoinFilter::filter($this->array, $this->join);
32 changes: 32 additions & 0 deletions tests/QueryBuilderTest.php
Original file line number Diff line number Diff line change
@@ -153,6 +153,38 @@ public function it_should_get_results_with_no_criteria_applied()
}
}

/**
* @test
*/
public function it_should_get_the_first_result_with_no_criteria_applied()
{
foreach ($this->usersArrays as $array) {
$qb = QueryBuilder::create($array);

$first = $qb->getFirstResult();

$this->assertEquals(1, $first['id']);
$this->assertEquals('Leanne Graham', $first['name']);
$this->assertEquals('[email protected]', $first['email']);
}
}

/**
* @test
*/
public function it_should_get_the_last_result_with_no_criteria_applied()
{
foreach ($this->usersArrays as $array) {
$qb = QueryBuilder::create($array);

$last = $qb->getLastResult();

$this->assertEquals(10, $last['id']);
$this->assertEquals('Clementina DuBuque', $last['name']);
$this->assertEquals('[email protected]', $last['email']);
}
}

/**
* @test
*/

0 comments on commit 87df9bc

Please sign in to comment.