Skip to content

Commit 8c7e10e

Browse files
authored
Merge pull request #14 from irfanh94/fix_word_collection_iterator
fix word collection iterator and add tests
2 parents 3ef224f + 651f228 commit 8c7e10e

File tree

2 files changed

+42
-2
lines changed

2 files changed

+42
-2
lines changed

src/Collection/WordCollection.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,12 @@ public function next(): void {
2929
++$this->iteratorPosition;
3030
}
3131

32-
public function key(): mixed {
32+
public function key(): int {
3333
return $this->iteratorPosition;
3434
}
3535

3636
public function valid(): bool {
37-
return isset($this->iteratorPosition);
37+
return isset($this->items[$this->iteratorPosition]);
3838
}
3939

4040
public function rewind(): void {
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace WordCounter\Tests\Unit\Collection;
6+
7+
use PHPUnit\Framework\TestCase;
8+
use WordCounter\Collection\Word;
9+
use WordCounter\Collection\WordCollection;
10+
11+
class WordCollectionTest extends TestCase {
12+
13+
public function testCanIterateWords(): void {
14+
$expected = [
15+
new Word('first', 5),
16+
new Word('second', 6),
17+
];
18+
19+
$wordCollection = new WordCollection($expected);
20+
21+
$actual = [];
22+
foreach ($wordCollection as $word) {
23+
$actual[] = $word;
24+
}
25+
26+
self::assertEquals($expected, $actual);
27+
}
28+
29+
public function testCanOutputArray(): void {
30+
$words = [
31+
new Word('first', 5),
32+
new Word('second', 6),
33+
];
34+
35+
$wordCollection = new WordCollection($words);
36+
37+
self::assertEquals(['first', 'second'], $wordCollection->toArray());
38+
}
39+
40+
}

0 commit comments

Comments
 (0)