glen / throwable-generator

ThrowableGenerator

1.1.0 2018-07-26 12:03 UTC

This package is auto-updated.

Last update: 2024-08-29 03:21:02 UTC


README

用于生成器包装器,无论是否使用 Generator::throw 都能按顺序返回值。

从顶层视角来看,Generator::throw 会丢弃生成器的下一个值,但这个值并没有完全丢失,而是变成了 throw() 方法的返回值。

如果你想要通过 yield 返回值,这会相当不方便。

<?php
 
function generator() {
  foreach (range(1, 6) as $x) {
    try {
      yield $x;
    } catch (Throwable $e) {
      echo " !! exception: {$e->getMessage()}\n";
    }
  }
}

$generator = generator();

foreach ($generator as $x) {
  echo "process: $x\n";
  if ($x % 2 === 0) {
    $generator->throw(new RuntimeException($x));
  }
}

上述代码会打印

process: 1
process: 2
 !! exception: 2
process: 4
 !! exception: 4
process: 6
 !! exception: 6

即值 35 在使用 throw 时被“丢失”。这个库使得结果变为

process: 1
process: 2
 !! exception: 2
process: 3
process: 4
 !! exception: 4
process: 5
process: 6
 !! exception: 6

请参阅Stackoverflow上的问题和讨论

要使用这个类,请将你的原始生成器用这个类包裹起来

$generator = new ThrowableGenerator($generator);

注意:API 已更改,throw() 将返回空值而不是生成器的下一个值。