Last active
April 3, 2018 16:50
-
-
Save sroze/2ed22483b5fd35081b4fa31f02fd1a24 to your computer and use it in GitHub Desktop.
PHP generator throw/try/catch bug - Originally found by @soyuka [here](https://github.com/soyuka/symfony-messenger-redis/blob/a0cc87f9adc8925ff289afb6420c6c6b5e2b33fb/tests/trycatchyield.php)
This file contains 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 | |
// Expected output: | |
// Got exception do nothing | |
// Got message test2 | |
// Got message test3 | |
// Actual output: | |
// Got exception do nothing | |
// Got message test3 | |
class Message { | |
public $str; | |
public function __construct($str) { | |
$this->str = $str; | |
} | |
} | |
function receive(): iterable | |
{ | |
$messages = [new Message('test1'), new Message('test2'), new Message('test3')]; | |
while (true) { | |
if (null === $message = array_shift($messages)) { | |
break; | |
} | |
try { | |
yield $message; | |
} catch (\Throwable $e) { | |
echo 'Got exception do nothing'.PHP_EOL; | |
} | |
} | |
} | |
$throwed = false; | |
$handler = function ($t) use (&$throwed) { | |
if (false === $throwed) { | |
$throwed = true; | |
throw new \Exception('Fail'); | |
} | |
echo sprintf('Got message %s', $t->str).PHP_EOL; | |
}; | |
$iterator = receive(); | |
foreach ($iterator as $message) { | |
try { | |
$handler($message); | |
} catch (\Throwable $e) { | |
$iterator->throw($e); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment