Event.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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, $timerId) {
  93. unset($this->eventTimer[$timerId]);
  94. try {
  95. $func(...$args);
  96. } catch (Throwable $e) {
  97. $this->error($e);
  98. }
  99. });
  100. if (!$event->addTimer($delay)) {
  101. throw new RuntimeException("Event::addTimer($delay) failed");
  102. }
  103. $this->eventTimer[$timerId] = $event;
  104. return $timerId;
  105. }
  106. /**
  107. * {@inheritdoc}
  108. */
  109. public function offDelay(int $timerId): bool
  110. {
  111. if (isset($this->eventTimer[$timerId])) {
  112. $this->eventTimer[$timerId]->del();
  113. unset($this->eventTimer[$timerId]);
  114. return true;
  115. }
  116. return false;
  117. }
  118. /**
  119. * {@inheritdoc}
  120. */
  121. public function offRepeat(int $timerId): bool
  122. {
  123. return $this->offDelay($timerId);
  124. }
  125. /**
  126. * {@inheritdoc}
  127. */
  128. public function repeat(float $interval, callable $func, array $args = []): int
  129. {
  130. $className = $this->eventClassName;
  131. $timerId = $this->timerId++;
  132. $event = new $className($this->eventBase, -1, $className::TIMEOUT | $className::PERSIST, function () use ($func, $args) {
  133. try {
  134. $func(...$args);
  135. } catch (Throwable $e) {
  136. $this->error($e);
  137. }
  138. });
  139. if (!$event->addTimer($interval)) {
  140. throw new RuntimeException("Event::addTimer($interval) failed");
  141. }
  142. $this->eventTimer[$timerId] = $event;
  143. return $timerId;
  144. }
  145. /**
  146. * {@inheritdoc}
  147. */
  148. public function onReadable($stream, callable $func): void
  149. {
  150. $className = $this->eventClassName;
  151. $fdKey = (int)$stream;
  152. $event = new $this->eventClassName($this->eventBase, $stream, $className::READ | $className::PERSIST, $func, $stream);
  153. // @phpstan-ignore-next-line Negated boolean expression is always false.
  154. if (!$event || !$event->add()) {
  155. return;
  156. }
  157. $this->readEvents[$fdKey] = $event;
  158. }
  159. /**
  160. * {@inheritdoc}
  161. */
  162. public function offReadable($stream): bool
  163. {
  164. $fdKey = (int)$stream;
  165. if (isset($this->readEvents[$fdKey])) {
  166. $this->readEvents[$fdKey]->del();
  167. unset($this->readEvents[$fdKey]);
  168. return true;
  169. }
  170. return false;
  171. }
  172. /**
  173. * {@inheritdoc}
  174. */
  175. public function onWritable($stream, callable $func): void
  176. {
  177. $className = $this->eventClassName;
  178. $fdKey = (int)$stream;
  179. $event = new $this->eventClassName($this->eventBase, $stream, $className::WRITE | $className::PERSIST, $func, $stream);
  180. // @phpstan-ignore-next-line Negated boolean expression is always false.
  181. if (!$event || !$event->add()) {
  182. return;
  183. }
  184. $this->writeEvents[$fdKey] = $event;
  185. }
  186. /**
  187. * {@inheritdoc}
  188. */
  189. public function offWritable($stream): bool
  190. {
  191. $fdKey = (int)$stream;
  192. if (isset($this->writeEvents[$fdKey])) {
  193. $this->writeEvents[$fdKey]->del();
  194. unset($this->writeEvents[$fdKey]);
  195. return true;
  196. }
  197. return false;
  198. }
  199. /**
  200. * {@inheritdoc}
  201. */
  202. public function onSignal(int $signal, callable $func): void
  203. {
  204. $className = $this->eventClassName;
  205. $fdKey = $signal;
  206. $event = $className::signal($this->eventBase, $signal, $func);
  207. if (!$event || !$event->add()) {
  208. return;
  209. }
  210. $this->eventSignal[$fdKey] = $event;
  211. }
  212. /**
  213. * {@inheritdoc}
  214. */
  215. public function offSignal(int $signal): bool
  216. {
  217. $fdKey = $signal;
  218. if (isset($this->eventSignal[$fdKey])) {
  219. $this->eventSignal[$fdKey]->del();
  220. unset($this->eventSignal[$fdKey]);
  221. return true;
  222. }
  223. return false;
  224. }
  225. /**
  226. * {@inheritdoc}
  227. */
  228. public function deleteAllTimer(): void
  229. {
  230. foreach ($this->eventTimer as $event) {
  231. $event->del();
  232. }
  233. $this->eventTimer = [];
  234. }
  235. /**
  236. * {@inheritdoc}
  237. */
  238. public function run(): void
  239. {
  240. $this->eventBase->loop();
  241. }
  242. /**
  243. * {@inheritdoc}
  244. */
  245. public function stop(): void
  246. {
  247. $this->eventBase->exit();
  248. }
  249. /**
  250. * {@inheritdoc}
  251. */
  252. public function getTimerCount(): int
  253. {
  254. return count($this->eventTimer);
  255. }
  256. /**
  257. * {@inheritdoc}
  258. */
  259. public function setErrorHandler(callable $errorHandler): void
  260. {
  261. $this->errorHandler = $errorHandler;
  262. }
  263. /**
  264. * {@inheritdoc}
  265. */
  266. public function getErrorHandler(): ?callable
  267. {
  268. return $this->errorHandler;
  269. }
  270. /**
  271. * @param Throwable $e
  272. * @return void
  273. * @throws Throwable
  274. */
  275. public function error(Throwable $e): void
  276. {
  277. try {
  278. if (!$this->errorHandler) {
  279. throw new $e;
  280. }
  281. ($this->errorHandler)($e);
  282. } catch (Throwable $e) {
  283. // Cannot trigger an exception in the Event callback, otherwise it will cause an infinite loop
  284. echo $e;
  285. }
  286. }
  287. }