Skip to content

Commit

Permalink
[5.3] add $default parameter to query builder when() method (#15428)
Browse files Browse the repository at this point in the history
* add a $default parameter to the QB when() clause

allows you to specify a default in the case that the when() $value is false

* add new test for when() method to test $default

* remove extra spaces to make StyleCI happy

* use the correct index for the bindings in the test

* use the full bindings array
  • Loading branch information
tomschlick authored and taylorotwell committed Sep 14, 2016
1 parent b43cb92 commit 6cf003a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/Illuminate/Database/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -459,14 +459,17 @@ public function crossJoin($table, $first = null, $operator = null, $second = nul
*
* @param bool $value
* @param \Closure $callback
* @param \Closure $default
* @return \Illuminate\Database\Query\Builder
*/
public function when($value, $callback)
public function when($value, $callback, $default = null)
{
$builder = $this;

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

return $builder;
Expand Down
21 changes: 21 additions & 0 deletions tests/Database/DatabaseQueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,27 @@ public function testWhenCallback()
$this->assertEquals('select * from "users" where "email" = ?', $builder->toSql());
}

public function testWhenCallbackWithDefault()
{
$callback = function ($query) {
return $query->where('id', '=', 1);
};

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

$builder = $this->getBuilder();
$builder->select('*')->from('users')->when(true, $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');
$this->assertEquals('select * from "users" where "id" = ? and "email" = ?', $builder->toSql());
$this->assertEquals([0 => 2, 1 => 'foo'], $builder->getBindings());
}

public function testBasicWheres()
{
$builder = $this->getBuilder();
Expand Down

0 comments on commit 6cf003a

Please sign in to comment.