Event.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. declare(strict_types=1);
  15. namespace Workerman\Events;
  16. use EventBase;
  17. use RuntimeException;
  18. use Throwable;
  19. use function class_exists;
  20. use function count;
  21. /**
  22. * libevent eventloop
  23. */
  24. class Event implements EventInterface
  25. {
  26. /**
  27. * Event base.
  28. * @var EventBase
  29. */
  30. protected EventBase $eventBase;
  31. /**
  32. * All listeners for read event.
  33. * @var array
  34. */
  35. protected array $readEvents = [];
  36. /**
  37. * All listeners for write event.
  38. * @var array
  39. */
  40. protected array $writeEvents = [];
  41. /**
  42. * Event listeners of signal.
  43. * @var array
  44. */
  45. protected array $eventSignal = [];
  46. /**
  47. * All timer event listeners.
  48. * [func, args, event, flag, time_interval]
  49. * @var array
  50. */
  51. protected array $eventTimer = [];
  52. /**
  53. * Timer id.
  54. * @var int
  55. */
  56. protected int $timerId = 0;
  57. /**
  58. * Event class name.
  59. * @var string
  60. */
  61. protected string $eventClassName = '';
  62. /**
  63. * @var ?callable
  64. */
  65. protected $errorHandler = null;
  66. /**
  67. * Construct.
  68. * @return void
  69. */
  70. public function __construct()
  71. {
  72. if (class_exists('\\\\Event', false)) {
  73. $className = '\\\\Event';
  74. } else {
  75. $className = '\Event';
  76. }
  77. $this->eventClassName = $className;
  78. if (class_exists('\\\\EventBase', false)) {
  79. $className = '\\\\EventBase';
  80. } else {
  81. $className = '\EventBase';
  82. }
  83. $this->eventBase = new $className();
  84. }
  85. /**
  86. * {@inheritdoc}
  87. */
  88. public function delay(float $delay, callable $func, array $args = []): int
  89. {
  90. $className = $this->eventClassName;
  91. $timerId = $this->timerId++;
  92. $event = new $className($this->eventBase, -1, $className::TIMEOUT, function () use ($func, $args) {
  93. try {
  94. $func(...$args);
  95. } catch (Throwable $e) {
  96. $this->error($e);
  97. }
  98. });
  99. if (!$event->addTimer($delay)) {
  100. throw new RuntimeException("Event::addTimer($delay) failed");
  101. }
  102. $this->eventTimer[$timerId] = $event;
  103. return $timerId;
  104. }
  105. /**
  106. * {@inheritdoc}
  107. */
  108. public function offDelay(int $timerId): bool
  109. {
  110. if (isset($this->eventTimer[$timerId])) {
  111. $this->eventTimer[$timerId]->del();
  112. unset($this->eventTimer[$timerId]);
  113. return true;
  114. }
  115. return false;
  116. }
  117. /**
  118. * {@inheritdoc}
  119. */
  120. public function offRepeat(int $timerId): bool
  121. {
  122. return $this->offDelay($timerId);
  123. }
  124. /**
  125. * {@inheritdoc}
  126. */
  127. public function repeat(float $interval, callable $func, array $args = []): int
  128. {
  129. $className = $this->eventClassName;
  130. $timerId = $this->timerId++;
  131. $event = new $className($this->eventBase, -1, $className::TIMEOUT | $className::PERSIST, function () use ($func, $args) {
  132. try {
  133. $func(...$args);
  134. } catch (Throwable $e) {
  135. $this->error($e);
  136. }
  137. });
  138. if (!$event->addTimer($interval)) {
  139. throw new RuntimeException("Event::addTimer($interval) failed");
  140. }
  141. $this->eventTimer[$timerId] = $event;
  142. return $timerId;
  143. }
  144. /**
  145. * {@inheritdoc}
  146. */
  147. public function onReadable($stream, callable $func): void
  148. {
  149. $className = $this->eventClassName;
  150. $fdKey = (int)$stream;
  151. $event = new $this->eventClassName($this->eventBase, $stream, $className::READ | $className::PERSIST, $func, $stream);
  152. // @phpstan-ignore-next-line Negated boolean expression is always false.
  153. if (!$event || !$event->add()) {
  154. return;
  155. }
  156. $this->readEvents[$fdKey] = $event;
  157. }
  158. /**
  159. * {@inheritdoc}
  160. */
  161. public function offReadable($stream): bool
  162. {
  163. $fdKey = (int)$stream;
  164. if (isset($this->readEvents[$fdKey])) {
  165. $this->readEvents[$fdKey]->del();
  166. unset($this->readEvents[$fdKey]);
  167. return true;
  168. }
  169. return false;
  170. }
  171. /**
  172. * {@inheritdoc}
  173. */
  174. public function onWritable($stream, callable $func): void
  175. {
  176. $className = $this->eventClassName;
  177. $fdKey = (int)$stream;
  178. $event = new $this->eventClassName($this->eventBase, $stream, $className::WRITE | $className::PERSIST, $func, $stream);
  179. // @phpstan-ignore-next-line Negated boolean expression is always false.
  180. if (!$event || !$event->add()) {
  181. return;
  182. }
  183. $this->writeEvents[$fdKey] = $event;
  184. }
  185. /**
  186. * {@inheritdoc}
  187. */
  188. public function offWritable($stream): bool
  189. {
  190. $fdKey = (int)$stream;
  191. if (isset($this->writeEvents[$fdKey])) {
  192. $this->writeEvents[$fdKey]->del();
  193. unset($this->writeEvents[$fdKey]);
  194. return true;
  195. }
  196. return false;
  197. }
  198. /**
  199. * {@inheritdoc}
  200. */
  201. public function onSignal(int $signal, callable $func): void
  202. {
  203. $className = $this->eventClassName;
  204. $fdKey = $signal;
  205. $event = $className::signal($this->eventBase, $signal, $func);
  206. if (!$event || !$event->add()) {
  207. return;
  208. }
  209. $this->eventSignal[$fdKey] = $event;
  210. }
  211. /**
  212. * {@inheritdoc}
  213. */
  214. public function offSignal(int $signal): bool
  215. {
  216. $fdKey = $signal;
  217. if (isset($this->eventSignal[$fdKey])) {
  218. $this->eventSignal[$fdKey]->del();
  219. unset($this->eventSignal[$fdKey]);
  220. return true;
  221. }
  222. return false;
  223. }
  224. /**
  225. * {@inheritdoc}
  226. */
  227. public function deleteAllTimer(): void
  228. {
  229. foreach ($this->eventTimer as $event) {
  230. $event->del();
  231. }
  232. $this->eventTimer = [];
  233. }
  234. /**
  235. * {@inheritdoc}
  236. */
  237. public function run(): void
  238. {
  239. $this->eventBase->loop();
  240. }
  241. /**
  242. * {@inheritdoc}
  243. */
  244. public function stop(): void
  245. {
  246. $this->eventBase->exit();
  247. }
  248. /**
  249. * {@inheritdoc}
  250. */
  251. public function getTimerCount(): int
  252. {
  253. return count($this->eventTimer);
  254. }
  255. /**
  256. * {@inheritdoc}
  257. */
  258. public function setErrorHandler(callable $errorHandler): void
  259. {
  260. $this->errorHandler = $errorHandler;
  261. }
  262. /**
  263. * {@inheritdoc}
  264. */
  265. public function getErrorHandler(): ?callable
  266. {
  267. return $this->errorHandler;
  268. }
  269. /**
  270. * @param Throwable $e
  271. * @return void
  272. * @throws Throwable
  273. */
  274. public function error(Throwable $e): void
  275. {
  276. try {
  277. if (!$this->errorHandler) {
  278. throw new $e;
  279. }
  280. ($this->errorHandler)($e);
  281. } catch (Throwable $e) {
  282. // Cannot trigger an exception in the Event callback, otherwise it will cause an infinite loop
  283. echo $e;
  284. }
  285. }
  286. }