Permalink
Browse files

Merge pull request #2858 from anlutro-pull-requests/collection-first

array_first functionality in Collection
  • Loading branch information...
taylorotwell committed Dec 4, 2013
2 parents a81bc41 + 59387d8 commit d600ebe7c2e76ca98c5ed280d77107a4159acfc4
Showing with 27 additions and 2 deletions.
  1. +11 −2 src/Illuminate/Support/Collection.php
  2. +16 −0 tests/Support/SupportCollectionTest.php
@@ -97,11 +97,20 @@ public function put($key, $value)
/**
* Get the first item from the collection.
*
* @param \Closure $callback
* @param mixed $default
* @return mixed|null
*/
public function first()
public function first(Closure $callback = null, $default = null)
{
return count($this->items) > 0 ? reset($this->items) : null;
if (is_null($callback))
{
return count($this->items) > 0 ? reset($this->items) : null;
}
else
{
return array_first($this->items, $callback, $default);
}
}
/**
@@ -294,6 +294,22 @@ public function testTransform()
$this->assertEquals(array('rolyat', 'niloc', 'nwahs'), array_values($data->all()));
}
public function testFirstWithCallback()
{
$data = new Collection(array('foo', 'bar', 'baz'));
$result = $data->first(function($key, $value) { return $value === 'bar'; });
$this->assertEquals('bar', $result);
}
public function testFirstWithCallbackAndDefault()
{
$data = new Collection(array('foo', 'bar'));
$result = $data->first(function($key, $value) { return $value === 'baz'; }, 'default');
$this->assertEquals('default', $result);
}
}
class TestAccessorEloquentTestStub

0 comments on commit d600ebe

Please sign in to comment.