refactor
[m6w6/seekat] / examples / ev.php
1 <?php
2
3
4 class EvHandler implements http\Client\Curl\User
5 {
6 private $client;
7 private $run;
8 private $ios = [];
9 private $timeout;
10
11 function __construct(http\Client $client) {
12 $this->client = $client;
13 }
14
15 function init($run) {
16 $this->run = $run;
17 }
18
19 function timer(int $timeout_ms) {
20 if (isset($this->timeout)) {
21 $this->timeout->set($timeout_ms/1000, 0);
22 $this->timeout->start();
23 } else {
24 $this->timeout = new EvTimer($timeout_ms/1000, 0, function() {
25 if (!call_user_func($this->run, $this->client)) {
26 if ($this->timeout) {
27 $this->timeout->stop();
28 $this->timeout = null;
29 }
30 }
31 });
32 }
33 }
34
35 function socket($socket, int $action) {
36 switch ($action) {
37 case self::POLL_NONE:
38 break;
39 case self::POLL_REMOVE:
40 echo "U";
41 if (isset($this->ios[(int) $socket])) {
42 $this->ios[(int) $socket]->stop();
43 unset($this->ios[(int) $socket]);
44 }
45 break;
46 default:
47 $ev = 0;
48 if ($action & self::POLL_IN) {
49 $ev |= Ev::READ;
50 }
51 if ($action & self::POLL_OUT) {
52 $ev |= Ev::WRITE;
53 }
54 if (isset($this->ios[(int) $socket])) {
55 $this->ios[(int) $socket]->set($socket, $ev);
56 } else {
57 $this->ios[(int) $socket] = new EvIo($socket, $ev, function($watcher, $events) use($socket) {
58 $action = 0;
59 if ($events & Ev::READ) {
60 $action |= self::POLL_IN;
61 }
62 if ($events & Ev::WRITE) {
63 $action |= self::POLL_OUT;
64 }
65 if (!call_user_func($this->run, $this->client, $socket, $action)) {
66 if ($this->timeout) {
67 $this->timeout->stop();
68 $this->timeout = null;
69 }
70 }
71 });
72 }
73 break;
74 }
75 }
76
77 function once() {
78 echo "O";
79 Ev::run(EV::RUN_NOWAIT);
80 }
81 function wait(int $timeout_ms = null) {
82 echo "W";
83 Ev::run(EV::RUN_ONCE);
84 }
85 function send() {
86 echo "!";
87 Ev::verify();
88 Ev::run();
89 }
90 }