Skip to content

Commit

Permalink
Pass the condition value to "when"
Browse files Browse the repository at this point in the history
  • Loading branch information
JosephSilber committed Mar 19, 2017
1 parent 5b95f6c commit 7a7494b
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
4 changes: 2 additions & 2 deletions src/Illuminate/Database/Concerns/BuildsQueries.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,9 @@ public function when($value, $callback, $default = null)
$builder = $this;

if ($value) {
$builder = $callback($builder);
$builder = $callback($builder, $value);
} elseif ($default) {
$builder = $default($builder);
$builder = $default($builder, $value);
}

return $builder;
Expand Down
16 changes: 11 additions & 5 deletions tests/Database/DatabaseQueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,9 @@ public function testBasicTableWrapping()

public function testWhenCallback()
{
$callback = function ($query) {
$callback = function ($query, $condition) {
$this->assertTrue($condition);

return $query->where('id', '=', 1);
};

Expand All @@ -147,21 +149,25 @@ public function testWhenCallback()

public function testWhenCallbackWithDefault()
{
$callback = function ($query) {
$callback = function ($query, $condition) {
$this->assertEquals($condition, 'truthy');

return $query->where('id', '=', 1);
};

$default = function ($query) {
$default = function ($query, $condition) {
$this->assertEquals($condition, 0);

return $query->where('id', '=', 2);
};

$builder = $this->getBuilder();
$builder->select('*')->from('users')->when(true, $callback, $default)->where('email', 'foo');
$builder->select('*')->from('users')->when('truthy', $callback, $default)->where('email', 'foo');
$this->assertEquals('select * from "users" where "id" = ? and "email" = ?', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 'foo'], $builder->getBindings());

$builder = $this->getBuilder();
$builder->select('*')->from('users')->when(false, $callback, $default)->where('email', 'foo');
$builder->select('*')->from('users')->when(0, $callback, $default)->where('email', 'foo');
$this->assertEquals('select * from "users" where "id" = ? and "email" = ?', $builder->toSql());
$this->assertEquals([0 => 2, 1 => 'foo'], $builder->getBindings());
}
Expand Down

0 comments on commit 7a7494b

Please sign in to comment.