Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix limit and offset on ordered query builders #5932

Merged
merged 3 commits into from Apr 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 17 additions & 1 deletion src/Query/OrderedQueryBuilder.php
Expand Up @@ -12,6 +12,8 @@ class OrderedQueryBuilder implements Builder
protected $builder;
protected $order;
protected $ordered = false;
protected $limit;
protected $offset;

public function __construct(Builder $builder, $order = [])
{
Expand All @@ -34,7 +36,7 @@ public function get($columns = ['*'])
$results = $this->performFallbackOrdering($results);
}

return $results;
return $results->take($this->limit)->skip($this->offset)->values();
}

public function __call($method, $parameters)
Expand Down Expand Up @@ -65,4 +67,18 @@ private function performFallbackOrdering($results)
return $a <=> $b;
})->values();
}

public function limit($value)
{
$this->limit = $value;

return $this;
}

public function offset($value)
{
$this->offset = max(0, $value);

return $this;
}
}
45 changes: 45 additions & 0 deletions tests/Query/OrderedQueryBuilderTest.php
Expand Up @@ -92,4 +92,49 @@ public function it_wont_order_the_items_when_using_pagination()

$this->assertEquals('paginator', $results);
}

/** @test */
public function it_limits_after_the_results_have_been_retrieved()
{
$builder = $this->mock(Builder::class);
$builder->shouldReceive('limit')->never();
$builder->shouldReceive('get')->once()->andReturn(collect([
['id' => '1'],
['id' => '2'],
['id' => '3'],
['id' => '4'],
['id' => '5'],
]));

$results = (new OrderedQueryBuilder($builder, [4, 5, 2, 1, 3]))->limit(3)->get();

$this->assertEquals([
['id' => '4'],
['id' => '5'],
['id' => '2'],
], $results->all());
}

/** @test */
public function it_offsets_after_the_results_have_been_retrieved()
{
$builder = $this->mock(Builder::class);
$builder->shouldReceive('offset')->never();
$builder->shouldReceive('get')->once()->andReturn(collect([
['id' => '1'],
['id' => '2'],
['id' => '3'],
['id' => '4'],
['id' => '5'],
]));

$results = (new OrderedQueryBuilder($builder, [4, 5, 2, 1, 3]))->offset(1)->get();

$this->assertEquals([
['id' => '5'],
['id' => '2'],
['id' => '1'],
['id' => '3'],
], $results->all());
}
}