Last active
August 8, 2023 20:23
-
-
Save aklump/624b9d07ae5ed389b43049a7d6eee158 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace AKlump\PHPUnit; | |
| /** | |
| * Given a mock object make it iterable using $data. | |
| * | |
| * @url https://stackoverflow.com/a/32422586 | |
| * | |
| * @code | |
| * $mock = $this->createMock(\SomeClass::class); | |
| * (new MakeMockIterable())($mock, [ | |
| * 'lorem', | |
| * 'ipsum', | |
| * ]); | |
| * $values = []; | |
| * foreach ($mock as $value) { | |
| * $values[] = $value; | |
| * } | |
| * $this->assertSame('lorem', $values[0]); | |
| * $this->assertSame('ipsum', $values[1]); | |
| * @endcode | |
| */ | |
| class MakeMockIterable { | |
| public function __invoke(\PHPUnit\Framework\MockObject\MockObject $mock, array $data) { | |
| $iterator = new \ArrayIterator($data); | |
| $mock | |
| ->method('rewind') | |
| ->willReturnCallback(function () use ($iterator) { | |
| return $iterator->rewind(); | |
| }); | |
| $mock | |
| ->method('current') | |
| ->willReturnCallback(function () use ($iterator) { | |
| return $iterator->current(); | |
| }); | |
| $mock | |
| ->method('key') | |
| ->willReturnCallback(function () use ($iterator) { | |
| return $iterator->key(); | |
| }); | |
| $mock | |
| ->method('next') | |
| ->willReturnCallback(function () use ($iterator) { | |
| return $iterator->next(); | |
| }); | |
| $mock | |
| ->method('valid') | |
| ->willReturnCallback(function () use ($iterator) { | |
| return $iterator->valid(); | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment