diff --git a/README.md b/README.md index 81d1cea..0065dae 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/src/QueryBuilder.php b/src/QueryBuilder.php index 26170e4..11fcb87 100644 --- a/src/QueryBuilder.php +++ b/src/QueryBuilder.php @@ -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,6 +237,7 @@ private function applySortingFilter(array $array) /** * @param array $array + * * @return array */ private function applyLimitFilter(array $array) @@ -217,6 +245,9 @@ private function applyLimitFilter(array $array) return LimitFilter::filter($array, $this->limit); } + /** + * @return array + */ private function applyJoinFilter() { return JoinFilter::filter($this->array, $this->join); diff --git a/tests/QueryBuilderTest.php b/tests/QueryBuilderTest.php index 2f2b77b..2e22e64 100644 --- a/tests/QueryBuilderTest.php +++ b/tests/QueryBuilderTest.php @@ -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('Sincere@april.biz', $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('Rey.Padberg@karina.biz', $last['email']); + } + } + /** * @test */