Coroutine.php
2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\Engine;
use Hyperf\Engine\Contract\CoroutineInterface;
use Hyperf\Engine\Exception\CoroutineDestroyedException;
use Hyperf\Engine\Exception\RunningInNonCoroutineException;
use Hyperf\Engine\Exception\RuntimeException;
use Swoole\Coroutine as SwooleCo;
class Coroutine implements CoroutineInterface
{
/**
* @var callable
*/
private $callable;
/**
* @var int
*/
private $id;
public function __construct(callable $callable)
{
$this->callable = $callable;
}
public static function create(callable $callable, ...$data)
{
$coroutine = new static($callable);
$coroutine->execute(...$data);
return $coroutine;
}
public function execute(...$data)
{
$this->id = SwooleCo::create($this->callable, ...$data);
return $this;
}
public function getId()
{
if (is_null($this->id)) {
throw new RuntimeException('Coroutine was not be executed.');
}
return $this->id;
}
public static function id()
{
return SwooleCo::getCid();
}
public static function pid(?int $id = null)
{
if ($id) {
$cid = SwooleCo::getPcid($id);
if ($cid === false) {
throw new CoroutineDestroyedException(sprintf('Coroutine #%d has been destroyed.', $id));
}
} else {
$cid = SwooleCo::getPcid();
}
if ($cid === false) {
throw new RunningInNonCoroutineException('Non-Coroutine environment don\'t has parent coroutine id.');
}
return max(0, $cid);
}
public static function set(array $config)
{
SwooleCo::set($config);
}
/**
* @return null|\ArrayObject
*/
public static function getContextFor(?int $id = null)
{
if ($id === null) {
return SwooleCo::getContext();
}
return SwooleCo::getContext($id);
}
public static function defer(callable $callable)
{
SwooleCo::defer($callable);
}
}