Skip to content

Commit

Permalink
Don't iterate over all collection in Collection::firstOrFail (laravel…
Browse files Browse the repository at this point in the history
  • Loading branch information
bastien-phi authored and victorvilella committed Oct 12, 2021
1 parent e64ee03 commit 8de2c34
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/Illuminate/Collections/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -1146,13 +1146,15 @@ public function firstOrFail($key = null, $operator = null, $value = null)
? $this->operatorForWhere(...func_get_args())
: $key;

$items = $this->when($filter)->filter($filter);
$placeholder = new stdClass();

if ($items->isEmpty()) {
$item = $this->first($filter, $placeholder);

if ($item === $placeholder) {
throw new ItemNotFoundException;
}

return $items->first();
return $item;
}

/**
Expand Down
22 changes: 22 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,28 @@ public function testFirstOrFailDoesntThrowExceptionIfMoreThanOneItemExistsWithCa
);
}

/**
* @dataProvider collectionClassProvider
*/
public function testFirstOrFailStopsIteratingAtFirstMatch($collection)
{
$data = new $collection([
function () {
return false;
},
function () {
return true;
},
function () {
throw new Exception();
},
]);

$this->assertNotNull($data->firstOrFail(function ($callback) {
return $callback();
}));
}

/**
* @dataProvider collectionClassProvider
*/
Expand Down

0 comments on commit 8de2c34

Please sign in to comment.