Skip to content

Commit e931e3d

Browse files
author
Jarek Jakubowski
committed
Add first() method
1 parent 860322c commit e931e3d

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

src/JarJak/Collection/Collection.php

+11
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,17 @@ public function sort(?callable $comparator = null): self
120120
return static::from($array);
121121
}
122122

123+
public function first()
124+
{
125+
if ($this instanceof \IteratorAggregate) {
126+
// PHP 8: SplFixedArray no longer implements Iterator
127+
$this->getIterator()->rewind();
128+
return $this->getIterator()->current() ?: null;
129+
}
130+
$this->rewind();
131+
return $this->current() ?: null;
132+
}
133+
123134
public function jsonSerialize(): array
124135
{
125136
return $this->toArray();

tests/CollectionTest.php

+13
Original file line numberDiff line numberDiff line change
@@ -93,4 +93,17 @@ public function __construct(\DateTimeInterface ...$items)
9393

9494
$this->assertSame($expected, $result->toArray());
9595
}
96+
97+
public function testFirst(): void
98+
{
99+
$collection = Collection::from(range(1, 10));
100+
$sum = 0;
101+
foreach ($collection as $item) {
102+
// just iterate over it
103+
$sum += $item;
104+
}
105+
106+
$this->assertSame($collection->first(), 1);
107+
$this->assertSame(55, $sum);
108+
}
96109
}

0 commit comments

Comments
 (0)