Beispiel #1
0
 /**
  * @param \Generator $generator
  */
 public function __construct(\Generator $generator)
 {
     $this->generator = $generator;
     /**
      * @param \Throwable|null $exception Exception to be thrown into the generator.
      * @param mixed $value Value to be sent into the generator.
      */
     $this->when = function ($exception, $value) {
         if ($this->depth > self::MAX_CONTINUATION_DEPTH) {
             // Defer continuation to avoid blowing up call stack.
             Loop::defer(function () use($exception, $value) {
                 ($this->when)($exception, $value);
             });
             return;
         }
         try {
             if ($exception) {
                 // Throw exception at current execution point.
                 $yielded = $this->generator->throw($exception);
             } else {
                 // Send the new value and execute to next yield statement.
                 $yielded = $this->generator->send($value);
             }
             if ($yielded instanceof Promise) {
                 ++$this->depth;
                 $yielded->when($this->when);
                 --$this->depth;
                 return;
             }
             if ($this->generator->valid()) {
                 $got = \is_object($yielded) ? \get_class($yielded) : \gettype($yielded);
                 throw new InvalidYieldError($this->generator, \sprintf("Unexpected yield (%s expected, got %s)", Promise::class, $got));
             }
             $this->resolve($this->generator->getReturn());
         } catch (\Throwable $exception) {
             $this->dispose($exception);
         }
     };
     try {
         $yielded = $this->generator->current();
         if ($yielded instanceof Promise) {
             ++$this->depth;
             $yielded->when($this->when);
             --$this->depth;
             return;
         }
         if ($this->generator->valid()) {
             $got = \is_object($yielded) ? \get_class($yielded) : \gettype($yielded);
             throw new InvalidYieldError($this->generator, \sprintf("Unexpected yield (%s expected, got %s)", Promise::class, $got));
         }
         $this->resolve($this->generator->getReturn());
     } catch (\Throwable $exception) {
         $this->dispose($exception);
     }
 }
Beispiel #2
0
 public function run()
 {
     if (!$this->generator) {
         throw new Exception("");
     } elseif (!$this->closed) {
         throw new Exception("");
     }
     $this->closed = false;
     $this->generator->rewind();
     return $this->generator->current();
 }
Beispiel #3
0
 /**
  * {@inheritdoc}
  */
 public function tick()
 {
     if ($this->firstTick) {
         $this->firstTick = false;
         $this->deferred->notify(new MessageEvent($this, $this->generator->current()));
     } else {
         $this->deferred->notify(new MessageEvent($this, $this->generator->send(null)));
     }
     if (!$this->generator->valid()) {
         $this->deferred->resolve(new Event($this));
     }
 }
 /**
  * executes the current middleware
  *
  * @param ServerRequestInterface $request
  * @param ResponseInterface $response
  * @return ResponseInterface
  */
 private function call(ServerRequestInterface $request, ResponseInterface $response)
 {
     if ($this->atStart) {
         $middleware = $this->generator->current();
         $this->atStart = false;
     } else {
         $middleware = $this->generator->send(null);
     }
     if (!$middleware) {
         return $response;
     }
     $callable = $this->app->getMiddlewareCallable($middleware);
     return call_user_func($callable, $request, $response, $this->next);
 }
Beispiel #5
0
 /**
  * run coroutine
  * @return mixed
  */
 public function run()
 {
     if ($this->first_run) {
         $this->first_run = false;
         return $this->coroutine->current();
     }
     if ($this->exception instanceof \Exception) {
         $retval = $this->coroutine->throw($this->exception);
         $this->exception = null;
         return $retval;
     }
     $retval = $this->coroutine->send($this->send_value);
     $this->send_value = null;
     return $retval;
 }
Beispiel #6
0
 /**
  * Get current element
  *
  * Takes into account if the callback returns a Generator
  *
  * @return mixed
  */
 public function current()
 {
     if ($this->generator) {
         return $this->generator->current();
     }
     $callable = $this->callable;
     $result = $callable();
     if (!$this->generator && $this->generator !== false) {
         $this->generator = $result instanceof \Generator ? $result : false;
         if ($this->generator) {
             return $this->generator->current();
         }
     }
     return $result;
 }
Beispiel #7
0
 public function current()
 {
     if ($this->_currentGen) {
         return $this->_currentGen->current();
     }
     return current($this->_records);
 }
Beispiel #8
0
 private function execute(\Generator $generator)
 {
     $stack = [];
     //This is basically a simple iterative in-order tree traversal algorithm
     $yielded = $generator->current();
     //This is a depth-first traversal
     while ($yielded instanceof \Generator) {
         //... push it to the stack
         $stack[] = $generator;
         $generator = $yielded;
         $yielded = $generator->current();
     }
     while (!empty($stack)) {
         //We've reached the end of the branch, let's step back on the stack
         $generator = array_pop($stack);
         //step the generator
         $yielded = $generator->send($yielded);
         //Depth-first traversal
         while ($yielded instanceof \Generator) {
             //... push it to the stack
             $stack[] = $generator;
             $generator = $yielded;
             $yielded = $generator->current();
         }
     }
     return $yielded;
 }
 /**
  * Resolves yield calls tree
  * and gives a return value if outcome of yield is CoroutineReturnValue instance
  *
  * @param \Generator $coroutine nested coroutine tree
  * @return \Generator
  */
 private static function stackedCoroutine(\Generator $coroutine)
 {
     $stack = new \SplStack();
     while (true) {
         $value = $coroutine->current();
         // nested generator/coroutine
         if ($value instanceof \Generator) {
             $stack->push($coroutine);
             $coroutine = $value;
             continue;
         }
         // coroutine end or value is a value object instance
         if (!$coroutine->valid() || $value instanceof CoroutineReturnValue) {
             // if till this point, there are no coroutines in a stack thatn stop here
             if ($stack->isEmpty()) {
                 return;
             }
             $coroutine = $stack->pop();
             $value = $value instanceof CoroutineReturnValue ? $value->getValue() : null;
             $coroutine->send($value);
             continue;
         }
         $coroutine->send((yield $coroutine->key() => $value));
     }
 }
Beispiel #10
0
 /**
  *
  */
 private function initializeBeforeRead()
 {
     if ($this->generator === null) {
         $this->generator = $this->delegatedStream->read($this->blockSize);
         $this->resource = $this->generator->current();
         $this->resource->rewind();
     }
 }
Beispiel #11
0
 /**
  * [run 协程调度]
  * @param \Generator $gen
  * @throws \Exception
  */
 public function run(\Generator $gen)
 {
     while (true) {
         try {
             /* 异常处理 */
             if ($this->exception) {
                 $gen->throw($this->exception);
                 $this->exception = null;
                 continue;
             }
             $value = $gen->current();
             //                Logger::write(__METHOD__ . " value === " . var_export($value, true), Logger::INFO);
             /* 中断内嵌 继续入栈 */
             if ($value instanceof \Generator) {
                 $this->corStack->push($gen);
                 //                    Logger::write(__METHOD__ . " corStack push ", Logger::INFO);
                 $gen = $value;
                 continue;
             }
             /* if value is null and stack is not empty pop and send continue */
             if (is_null($value) && !$this->corStack->isEmpty()) {
                 //                    Logger::write(__METHOD__ . " values is null stack pop and send ", Logger::INFO);
                 $gen = $this->corStack->pop();
                 $gen->send($this->callbackData);
                 continue;
             }
             if ($value instanceof ReturnValue) {
                 $gen = $this->corStack->pop();
                 $gen->send($value->getValue());
                 // end yeild
                 //                    Logger::write(__METHOD__ . " yield end words == " . var_export($value, true), Logger::INFO);
                 continue;
             }
             /* 中断内容为异步IO 发包 返回 */
             if ($value instanceof \Swoole\Client\IBase) {
                 //async send push gen to stack
                 $this->corStack->push($gen);
                 $value->send(array($this, 'callback'));
                 return;
             }
             /* 出栈,回射数据 */
             if ($this->corStack->isEmpty()) {
                 return;
             }
             //                Logger::write(__METHOD__ . " corStack pop ", Logger::INFO);
             $gen = $this->corStack->pop();
             $gen->send($value);
         } catch (EasyWorkException $e) {
             if ($this->corStack->isEmpty()) {
                 throw $e;
             }
             $gen = $this->corStack->pop();
             $this->exception = $e;
         }
     }
 }
Beispiel #12
0
 /**
  * @param \Generator $generator
  */
 public function __construct(Generator $generator)
 {
     parent::__construct();
     $this->generator = $generator;
     /**
      * @param mixed $value The value to send to the generator.
      */
     $this->send = function ($value = null) {
         if ($this->busy) {
             Loop\queue($this->send, $value);
             // Queue continuation to avoid blowing up call stack.
             return;
         }
         try {
             // Send the new value and execute to next yield statement.
             $this->next($this->generator->send($value));
         } catch (Throwable $exception) {
             $this->reject($exception);
         }
     };
     /**
      * @param \Throwable $exception Exception to be thrown into the generator.
      */
     $this->capture = function (Throwable $exception) {
         if ($this->busy) {
             Loop\queue($this->capture, $exception);
             // Queue continuation to avoid blowing up call stack.
             return;
         }
         try {
             // Throw exception at current execution point.
             $this->next($this->generator->throw($exception));
         } catch (Throwable $exception) {
             $this->reject($exception);
         }
     };
     try {
         $this->next($this->generator->current());
     } catch (Throwable $exception) {
         $this->reject($exception);
     }
 }
Beispiel #13
0
 /**
  * Return value that generator has returned or thrown.
  * @return mixed
  */
 public function getReturnOrThrown()
 {
     $this->validateInvalidity();
     if ($this->e === null && $this->g->valid() && !$this->valid()) {
         return $this->g->current();
     }
     if ($this->e) {
         return $this->e;
     }
     return method_exists($this->g, 'getReturn') ? $this->g->getReturn() : null;
 }
Beispiel #14
0
 /**
  * @param \Generator $generator
  */
 public function __construct(Generator $generator)
 {
     parent::__construct();
     $this->generator = $generator;
     /**
      * @param mixed $value The value to send to the generator.
      */
     $this->send = function ($value = null) {
         if (null === $this->generator) {
             // Coroutine may have been cancelled.
             return;
         }
         try {
             // Send the new value and execute to next yield statement.
             $this->next($this->generator->send($value));
         } catch (Throwable $exception) {
             $this->reject($exception);
         }
     };
     /**
      * @param \Throwable $exception Exception to be thrown into the generator.
      */
     $this->capture = function (Throwable $exception) {
         if (null === $this->generator) {
             // Coroutine may have been cancelled.
             return;
         }
         try {
             // Throw exception at current execution point.
             $this->next($this->generator->throw($exception));
         } catch (Throwable $exception) {
             $this->reject($exception);
         }
     };
     try {
         $this->next($this->generator->current());
     } catch (Throwable $exception) {
         $this->reject($exception);
     }
 }
Beispiel #15
0
 /**
  * When you need to return Result from your function, and it also depends on another
  * functions returning Results, you can make it a generator function and yield
  * values from dependant functions, this pattern makes code less bloated with
  * statements like this:
  * $res = something();
  * if ($res instanceof Ok) {
  *     $something = $res->unwrap();
  * } else {
  *     return $res;
  * }
  *
  * Instead you can write:
  * $something = (yield something());
  *
  * @see /example.php
  *
  * @param \Generator $resultsGenerator Generator that produces Result instances
  * @return Result
  */
 public static function reduce(\Generator $resultsGenerator)
 {
     /** @var Result $result */
     $result = $resultsGenerator->current();
     while ($resultsGenerator->valid()) {
         if ($result instanceof Err) {
             return $result;
         }
         $tmpResult = $resultsGenerator->send($result->unwrap());
         if ($resultsGenerator->valid()) {
             $result = $tmpResult;
         }
     }
     return $result;
 }
Beispiel #16
0
 /**
  * @param \Generator $generator
  * @param string $prefix
  */
 public function __construct(\Generator $generator, string $prefix)
 {
     $yielded = $generator->current();
     $prefix .= \sprintf("; %s yielded at key %s", \is_object($yielded) ? \get_class($yielded) : \gettype($yielded), $generator->key());
     if (!$generator->valid()) {
         parent::__construct($prefix);
         return;
     }
     $reflGen = new \ReflectionGenerator($generator);
     $exeGen = $reflGen->getExecutingGenerator();
     if ($isSubgenerator = $exeGen !== $generator) {
         $reflGen = new \ReflectionGenerator($exeGen);
     }
     parent::__construct(\sprintf("%s on line %s in %s", $prefix, $reflGen->getExecutingLine(), $reflGen->getExecutingFile()));
 }
Beispiel #17
0
function stackedCoroutine(Generator $gen)
{
    $stack = new SplStack();
    $exception = null;
    for (;;) {
        try {
            if ($exception) {
                $gen->throw($exception);
                $exception = null;
                continue;
            }
            $value = $gen->current();
            if ($value instanceof Generator) {
                $stack->push($gen);
                $gen = $value;
                continue;
            }
            $isReturnValue = $value instanceof CoroutineReturnValue;
            if (!$gen->valid() || $isReturnValue) {
                if ($stack->isEmpty()) {
                    return;
                }
                $gen = $stack->pop();
                $gen->send($isReturnValue ? $value->getValue() : NULL);
                continue;
            }
            if ($value instanceof CoroutinePlainValue) {
                $value = $value->getValue();
            }
            try {
                $sendValue = (yield $gen->key() => $value);
            } catch (Exception $e) {
                $gen->throw($e);
                continue;
            }
            $gen->send($sendValue);
        } catch (Exception $e) {
            if ($stack->isEmpty()) {
                throw $e;
            }
            $gen = $stack->pop();
            $exception = $e;
        }
    }
}
Beispiel #18
0
 /**
  * {@inheritdoc}
  */
 public function cancel($reason = null)
 {
     if (null !== $this->generator) {
         $current = $this->generator->current();
         // Get last yielded value.
         if ($current instanceof Awaitable) {
             $current->cancel($reason);
             // Cancel last yielded awaitable.
         }
         try {
             $this->close();
             // Throwing finally blocks in the Generator may cause close() to throw.
         } catch (Throwable $exception) {
             $reason = $exception;
         }
     }
     parent::cancel($reason);
 }
Beispiel #19
0
 /**
  * [run 协程调度]
  * @param  Generator $gen [description]
  * @return [type]         [description]
  */
 public function run(\Generator $gen)
 {
     while (true) {
         try {
             /*
                异常处理
             */
             if ($this->exception) {
                 $gen->throw($this->exception);
                 $this->exception = null;
                 continue;
             }
             $value = $gen->current();
             \SysLog::info(__METHOD__ . " value === " . print_r($value, true), __CLASS__);
             /*
                中断内嵌 继续入栈
             */
             if ($value instanceof \Generator) {
                 $this->corStack->push($gen);
                 \SysLog::info(__METHOD__ . " corStack push ", __CLASS__);
                 $gen = $value;
                 continue;
             }
             /*
                if value is null and stack is not empty pop and send continue
             */
             if (is_null($value) && !$this->corStack->isEmpty()) {
                 \SysLog::info(__METHOD__ . " values is null stack pop and send", __CLASS__);
                 $gen = $this->corStack->pop();
                 $gen->send($this->callbackData);
                 continue;
             }
             if ($value instanceof Swoole\Coroutine\RetVal) {
                 // end yeild
                 \SysLog::info(__METHOD__ . " yield end words == " . print_r($value, true), __CLASS__);
                 return false;
             }
             /*
                中断内容为异步IO 发包 返回
             */
             if (is_subclass_of($value, 'Swoole\\Client\\Base')) {
                 //async send push gen to stack
                 $this->corStack->push($gen);
                 $value->send(array($this, 'callback'));
                 return;
             }
             /*
                出栈,回射数据
             */
             if ($this->corStack->isEmpty()) {
                 return;
             }
             \SysLog::info(__METHOD__ . " corStack pop ", __CLASS__);
             $gen = $this->corStack->pop();
             $gen->send($value);
         } catch (\Exception $e) {
             if ($this->corStack->isEmpty()) {
                 /*
                     throw the exception 
                 */
                 \SysLog::error(__METHOD__ . " exception ===" . $e->getMessage(), __CLASS__);
                 return;
             }
         }
     }
 }
Beispiel #20
0
 /**
  * @brief 协程堆栈调度
  * @return type
  */
 public function run(\Generator $generator)
 {
     for (;;) {
         try {
             //异常处理
             if (null !== $this->_exception) {
                 $generator->throw($this->_exception);
                 $this->_exception = null;
                 continue;
             }
             //协程堆栈链的下一个元素
             $current = $generator->current();
             //协程堆栈链表的中断内嵌
             if ($current instanceof \Generator) {
                 $this->_coroutineStack->push($generator);
                 $generator = $current;
                 continue;
             }
             //syscall中断
             if ($current instanceof \Aha\Coroutine\SystemCall) {
                 return $current;
             }
             //retval中断
             $isReturnValue = $current instanceof \Aha\Coroutine\RetVal;
             if (!$generator->valid() || $isReturnValue) {
                 if ($this->_coroutineStack->isEmpty()) {
                     return;
                 }
                 $generator = $this->_coroutineStack->pop();
                 $generator->send($isReturnValue ? $current->getvalue() : $this->_sendValue);
                 $this->_sendValue = null;
             }
             //异步网络IO中断
             if ($this->_ahaInterrupt($current)) {
                 $this->_coroutineStack->push($generator);
                 return;
             }
             //当前协程堆栈元素可能有多次yeild 但是与父协程只有一次通信的机会 在通信前运行完
             $generator->send(is_null($current) ? $this->_sendValue : $current);
             $this->_sendValue = null;
             while ($generator->valid()) {
                 $current = $generator->current();
                 $generator->send(is_null($current) ? $this->_sendValue : $current);
                 $this->_sendValue = null;
             }
             //协程栈是空的 已经调度完毕
             if ($this->_coroutineStack->isEmpty()) {
                 return;
             }
             //把当前结果传给父协程栈
             $generator = $this->_coroutineStack->pop();
             $data = is_null($current) ? $this->_sendValue : $current;
             $this->_sendValue = null;
             $generator->send($data);
         } catch (\Exception $ex) {
             echo "[Coroutine_Task_Run_Exception]" . $ex->getMessage() . PHP_EOL;
             if ($this->_coroutineStack->isEmpty()) {
                 return;
             }
         }
     }
 }
Beispiel #21
0
 public function current()
 {
     return $this->generator->current();
 }
Beispiel #22
0
function asyncCaller(Generator $gen)
{
    global $cmd;
    $r = $gen->current();
    if (isset($r)) {
        switch ($r[0]) {
            case 'rpc':
                foreach (glob(__DIR__ . '/rpc/*.php') as $start_file) {
                    exec($cmd . ' ' . $start_file);
                }
                echo "rpc SERVEICE START ...\n";
                //thrift 的rpc远程调用服务
                $gen->send('rpc SERVEICE SUCCESS!');
                asyncCaller($gen);
                break;
            case 'mysqlpool':
                foreach (glob(__DIR__ . '/mysql/*.php') as $start_file) {
                    exec($cmd . ' ' . $start_file);
                }
                echo "mysqlpool SERVEICE START ...\n";
                //数据库连接池服务
                $gen->send('mysqlpool SERVEICE SUCCESS!');
                asyncCaller($gen);
                break;
            case 'vmstat':
                foreach (glob(__DIR__ . '/swoole/Vm*.php') as $start_file) {
                    exec($cmd . ' ' . $start_file);
                }
                echo "vmstat SERVEICE START ...\n";
                //硬件监控服务
                $gen->send('vmstat SERVEICE SUCCESS!');
                asyncCaller($gen);
                break;
            case 'swoolelive':
                foreach (glob(__DIR__ . '/swoole/SwooleLiveServer.php') as $start_file) {
                    exec($cmd . ' ' . $start_file);
                }
                echo "swoolelive SERVEICE START ...\n";
                //网络直播服务
                $gen->send('swoolelive SERVEICE SUCCESS!');
                asyncCaller($gen);
                break;
            case 'task':
                foreach (glob(__DIR__ . '/swoole/Task*.php') as $start_file) {
                    exec($cmd . ' ' . $start_file);
                }
                echo "task SERVEICE START ...\n";
                //任务服务器服务
                $gen->send('task SERVEICE SUCCESS!');
                asyncCaller($gen);
                break;
            case 'distributed':
                foreach (glob(__DIR__ . '/distributed/*.php') as $start_file) {
                    exec($cmd . ' ' . $start_file);
                }
                echo "distributed SERVEICE START ...\n";
                //分布式服务器通讯服务
                $gen->send('distributed SERVEICE SUCCESS!');
                asyncCaller($gen);
                break;
            case 'hprose':
                foreach (glob(__DIR__ . '/hprose/*.php') as $start_file) {
                    exec($cmd . ' ' . $start_file);
                }
                echo "hprose SERVEICE START ...\n";
                //hprose提供rpc服务
                $gen->send('hprose SERVEICE SUCCESS!');
                asyncCaller($gen);
                break;
            default:
                $gen->send('no method');
                asyncCaller($gen);
                break;
        }
    }
}
Beispiel #23
0
 /**
  * @param \Generator $generator
  */
 public function __construct(Generator $generator)
 {
     $this->generator = $generator;
     parent::__construct(function (callable $resolve, callable $reject) {
         /**
          * @param mixed $value The value to send to the generator.
          * @param \Throwable|null $exception Exception object to be thrown into the generator if not null.
          */
         $this->worker = function ($value = null, Throwable $exception = null) use($resolve, $reject) {
             if ($this->paused) {
                 // If paused, mark coroutine as ready to resume.
                 $this->ready = true;
                 return;
             }
             try {
                 if ($this->initial) {
                     // Get result of first yield statement.
                     $this->initial = false;
                     $this->current = $this->generator->current();
                 } elseif (null !== $exception) {
                     // Throw exception at current execution point.
                     $this->current = $this->generator->throw($exception);
                 } else {
                     // Send the new value and execute to next yield statement.
                     $this->current = $this->generator->send($value);
                 }
                 if (!$this->generator->valid()) {
                     $resolve($this->generator->getReturn());
                     $this->close();
                     return;
                 }
                 if ($this->current instanceof Generator) {
                     $this->current = new self($this->current);
                 }
                 if ($this->current instanceof PromiseInterface) {
                     $this->current->done($this->worker, $this->capture);
                 } else {
                     Loop\queue($this->worker, $this->current);
                 }
             } catch (Throwable $exception) {
                 $reject($exception);
                 $this->close();
             }
         };
         /**
          * @param \Throwable $exception Exception to be thrown into the generator.
          */
         $this->capture = function (Throwable $exception) {
             if (null !== $this->worker) {
                 // Coroutine may have been closed.
                 ($this->worker)(null, $exception);
             }
         };
         Loop\queue($this->worker);
         return function (Throwable $exception) {
             try {
                 $current = $this->generator->current();
                 // Get last yielded value.
                 while ($this->generator->valid()) {
                     if ($current instanceof PromiseInterface) {
                         $current->cancel($exception);
                     }
                     $current = $this->generator->throw($exception);
                 }
             } finally {
                 $this->close();
             }
         };
     });
 }
 /**
  * @inheritdoc
  */
 public function getChildren()
 {
     return new self($this->generator->current());
 }
Beispiel #25
0
 /**
  * Returns the current token in the lexer generator.
  *
  * @see \Generator->current
  *
  * @return array the token array (always _one_ token, as an array)
  */
 protected function getToken()
 {
     return $this->tokens->current();
 }
Beispiel #26
0
 /**
  * @param \Generator $generator
  */
 public function __construct(Generator $generator)
 {
     $this->generator = $generator;
     parent::__construct(function (callable $resolve, callable $reject) {
         $yielded = $this->generator->current();
         if (!$this->generator->valid()) {
             $resolve($this->generator->getReturn());
             $this->close();
             return;
         }
         /**
          * @param mixed $value The value to send to the generator.
          */
         $this->send = function ($value = null) use($resolve, $reject) {
             if ($this->paused) {
                 // If paused, save callable and value for resuming.
                 $this->next = [$this->send, $value];
                 return;
             }
             try {
                 // Send the new value and execute to next yield statement.
                 $yielded = $this->generator->send($value);
                 if (!$this->generator->valid()) {
                     $resolve($this->generator->getReturn());
                     $this->close();
                     return;
                 }
                 $this->next($yielded);
             } catch (Throwable $exception) {
                 $reject($exception);
                 $this->close();
             }
         };
         /**
          * @param \Throwable $exception Exception to be thrown into the generator.
          */
         $this->capture = function (Throwable $exception) use($resolve, $reject) {
             if ($this->paused) {
                 // If paused, save callable and exception for resuming.
                 $this->next = [$this->capture, $exception];
                 return;
             }
             try {
                 // Throw exception at current execution point.
                 $yielded = $this->generator->throw($exception);
                 if (!$this->generator->valid()) {
                     $resolve($this->generator->getReturn());
                     $this->close();
                     return;
                 }
                 $this->next($yielded);
             } catch (Throwable $exception) {
                 $reject($exception);
                 $this->close();
             }
         };
         $this->next($yielded);
         return function (Throwable $exception) {
             try {
                 $current = $this->generator->current();
                 // Get last yielded value.
                 if ($current instanceof PromiseInterface) {
                     $current->cancel($exception);
                 }
             } finally {
                 $this->close();
             }
         };
     });
 }
Beispiel #27
0
 public function current()
 {
     if (!$this->generator) {
         $this->rewind();
     }
     return $this->generator->current();
 }
/**
 *
 * @param int $n
 * @param \Generator $gen
 *
 * @return \Generator
 */
function take($n, Generator $gen)
{
    while ($n-- > 0 && $gen->valid()) {
        (yield $gen->current());
        $gen->next();
    }
}
Beispiel #29
0
function stackedCoroutine(Generator $gen)
{
    $stack = new SplStack();
    echo "stack------\n";
    $i = 0;
    $exception = null;
    for (;;) {
        try {
            $i++;
            echo "i:::{$i}\n";
            if ($exception) {
                echo "stack exception \n ";
                var_dump($exception);
                $gen->throw($exception);
                $exception = null;
                continue;
            }
            $value = $gen->current();
            echo "stacked current  value:\n";
            var_dump($value);
            if ($value instanceof Generator) {
                echo "stacked is generator\n";
                $stack->push($gen);
                $gen = $value;
                continue;
            }
            $isReturnValue = $value instanceof CoroutineReturnValue;
            if (!$gen->valid() || $isReturnValue) {
                echo "stack empty\n";
                if ($stack->isEmpty()) {
                    return;
                }
                echo "stacked pop\n";
                var_dump($isReturnValue);
                $gen = $stack->pop();
                var_dump($gen);
                $gen->send($isReturnValue ? $value->getValue() : NULL);
                continue;
            }
            echo "stacked before end\n";
            //$gen->send("stack send 1");
            //  yield ;
            try {
                $s = (yield $gen->key() => $value);
                echo "stacked before end -----{$s}\n";
            } catch (Exception $e) {
                echo "stack sendvalue exception\n";
                var_dump($e);
                $gen->throw($e);
                continue;
            }
            $re = $gen->send($s);
            var_dump("stack:");
            var_dump($re);
            echo "stacked  end\n";
        } catch (Exception $e) {
            echo "stack exception last\n";
            var_dump($e);
            if ($stack->isEmpty()) {
                throw $e;
            }
            $gen = $stask->pop();
            $exception = $e;
        }
    }
}
Beispiel #30
0
function stackedCoroutine(Generator $gen)
{
    $stack = new SplStack();
    for (;;) {
        $value = $gen->current();
        if ($value instanceof Generator) {
            $stack->push($gen);
            $gen = $value;
            continue;
        }
        $isReturnValue = $value instanceof CoroutineReturnValue;
        if (!$gen->valid() || $isReturnValue) {
            if ($stack->isEmpty()) {
                return;
            }
            $gen = $stack->pop();
            $gen->send($isReturnValue ? $value->getValue() : NULL);
            continue;
        }
        $gen->send((yield $gen->key() => $value));
    }
}