Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/glensc/throwablegenerator
Generator wrapper for yield be sequential regardless of using Generator::throw
https://github.com/glensc/throwablegenerator
Last synced: about 2 months ago
JSON representation
Generator wrapper for yield be sequential regardless of using Generator::throw
- Host: GitHub
- URL: https://github.com/glensc/throwablegenerator
- Owner: glensc
- License: mit
- Created: 2018-07-18T08:11:34.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2019-04-29T10:51:41.000Z (over 5 years ago)
- Last Synced: 2024-11-16T23:45:52.492Z (about 2 months ago)
- Language: PHP
- Size: 13.7 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# ThrowableGenerator
Generator wrapper for yield be sequential regardless of using [Generator::throw].
From top level view, [Generator::throw] discards next value from generator,
but it's not completely lost, but instead it becames return value of `throw()` method.This is rather inconvenient if you want values be returned by `yield`.
```php
getMessage()}\n";
}
}
}$generator = generator();
foreach ($generator as $x) {
echo "process: $x\n";
if ($x % 2 === 0) {
$generator->throw(new RuntimeException($x));
}
}
```The above code prints:
```text
process: 1
process: 2
!! exception: 2
process: 4
!! exception: 4
process: 6
!! exception: 6
```i.e values `3` and `5` were "lost" by using `throw`. This library makes result to be:
```text
process: 1
process: 2
!! exception: 2
process: 3
process: 4
!! exception: 4
process: 5
process: 6
!! exception: 6
```See question and discussion on [stackoverflow post]
[Generator::throw]: http://php.net/manual/en/generator.throw.php
[stackoverflow post]: https://stackoverflow.com/questions/51382259/why-in-php-using-generatorthrow-omits-yielded-values-after-throwTo use this class, wrap your original generator with this class:
```php
$generator = new ThrowableGenerator($generator);
```Note: There is API change, `throw()` will return nothing instead of next value from generator.