|
12 | 12 | use PHPUnit\Framework\TestCase; |
13 | 13 | use stdClass; |
14 | 14 |
|
| 15 | +use function Constructo\Cast\stringify; |
| 16 | + |
15 | 17 | final class CollectionTest extends TestCase |
16 | 18 | { |
17 | 19 | public function testShouldCreateFromArray(): void |
@@ -61,4 +63,75 @@ public function testShouldAllowNonStrictMode(): void |
61 | 63 | $this->assertCount(1, $collection); |
62 | 64 | $this->assertInstanceOf(Datum::class, $collection->all()[0]); |
63 | 65 | } |
| 66 | + |
| 67 | + public function testShouldFindMatchingItem(): void |
| 68 | + { |
| 69 | + $collection = new Collection(); |
| 70 | + $stub1 = new Stub('foo'); |
| 71 | + $stub2 = new Stub('bar'); |
| 72 | + $stub3 = new Stub('baz'); |
| 73 | + |
| 74 | + $collection->push($stub1); |
| 75 | + $collection->push($stub2); |
| 76 | + $collection->push($stub3); |
| 77 | + |
| 78 | + $result = $collection->find(fn ($item) => $item->value === 'bar'); |
| 79 | + |
| 80 | + $this->assertSame($stub2, $result); |
| 81 | + } |
| 82 | + |
| 83 | + public function testShouldReturnNullWhenNoMatchFound(): void |
| 84 | + { |
| 85 | + $collection = new Collection(); |
| 86 | + $stub1 = new Stub('foo'); |
| 87 | + $stub2 = new Stub('bar'); |
| 88 | + |
| 89 | + $collection->push($stub1); |
| 90 | + $collection->push($stub2); |
| 91 | + |
| 92 | + $result = $collection->find(fn ($item) => $item->value === 'nonexistent'); |
| 93 | + |
| 94 | + $this->assertNull($result); |
| 95 | + } |
| 96 | + |
| 97 | + public function testShouldReturnNullWhenFindingInEmptyCollection(): void |
| 98 | + { |
| 99 | + $collection = new Collection(); |
| 100 | + |
| 101 | + $result = $collection->find(fn ($item) => $item->value === 'anything'); |
| 102 | + |
| 103 | + $this->assertNull($result); |
| 104 | + } |
| 105 | + |
| 106 | + public function testShouldReturnFirstMatchWhenMultipleMatches(): void |
| 107 | + { |
| 108 | + $collection = new Collection(); |
| 109 | + $stub1 = new Stub('same'); |
| 110 | + $stub2 = new Stub('same'); |
| 111 | + $stub3 = new Stub('different'); |
| 112 | + |
| 113 | + $collection->push($stub1); |
| 114 | + $collection->push($stub2); |
| 115 | + $collection->push($stub3); |
| 116 | + |
| 117 | + $result = $collection->find(fn ($item) => $item->value === 'same'); |
| 118 | + |
| 119 | + $this->assertSame($stub1, $result); |
| 120 | + } |
| 121 | + |
| 122 | + public function testShouldFindWithComplexClosure(): void |
| 123 | + { |
| 124 | + $collection = new Collection(); |
| 125 | + $stub1 = new Stub('short'); |
| 126 | + $stub2 = new Stub('verylongvalue'); |
| 127 | + $stub3 = new Stub('medium'); |
| 128 | + |
| 129 | + $collection->push($stub1); |
| 130 | + $collection->push($stub2); |
| 131 | + $collection->push($stub3); |
| 132 | + |
| 133 | + $result = $collection->find(fn ($item) => strlen(stringify($item->value)) > 8); |
| 134 | + |
| 135 | + $this->assertSame($stub2, $result); |
| 136 | + } |
64 | 137 | } |
0 commit comments