From 7a2536389f35bc100c13bfacb8fb2d4be376f574 Mon Sep 17 00:00:00 2001 From: danilopolani Date: Sat, 10 Apr 2021 18:04:16 +0200 Subject: [PATCH] allow a callback on connection to be executed --- src/Client.php | 17 +++++++++++++---- src/ClientOptions.php | 5 +++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/Client.php b/src/Client.php index 14463fc..301b3e5 100644 --- a/src/Client.php +++ b/src/Client.php @@ -42,7 +42,7 @@ public function __construct(ClientOptions $options) $this->eventHandler = new EventHandler(); } - public function connect(): void + public function connect(?callable $execute = null): void { $tcpConnector = new TcpConnector($this->loop); $dnsResolverFactory = new Factory(); @@ -50,7 +50,7 @@ public function connect(): void $dnsConnector = new DnsConnector($tcpConnector, $dns); $connectorPromise = $this->getConnectorPromise($dnsConnector); - $connectorPromise->then(function (ConnectionInterface $connection) { + $connectorPromise->then(function (ConnectionInterface $connection) use ($execute) { $this->connection = $connection; $this->connected = true; $this->channels = []; @@ -69,9 +69,12 @@ public function connect(): void } }); - $this->connection->on('close', function () { + $this->connection->on('close', function () use ($execute) { $this->connected = false; - $this->reconnect('Connection closed by Twitch.'); + + if (is_null($execute)) { + $this->reconnect('Connection closed by Twitch.'); + } }); $this->connection->on('end', function () { @@ -83,6 +86,12 @@ public function connect(): void $this->write("PASS {$identity['password']}"); $this->write("NICK {$identity['username']}"); $this->write('CAP REQ :twitch.tv/membership twitch.tv/tags twitch.tv/commands'); + + if (!is_null($execute)) { + $this->loop->addTimer($this->options->getExecutionTimeout(), fn () => $this->close()); + + $execute(); + } }, fn($error) => $this->reconnect($error)); $this->loop->run(); diff --git a/src/ClientOptions.php b/src/ClientOptions.php index 67afe93..8ae7aa8 100644 --- a/src/ClientOptions.php +++ b/src/ClientOptions.php @@ -16,6 +16,11 @@ public function isDebug(): bool return $this->options['options']['debug'] ?? false; } + public function getExecutionTimeout(): float + { + return (float) ($this->options['options']['execution_timeout'] ?? 1.5); + } + public function getIdentity(): array { $default = ['username' => 'justinfan' . random_int(1000, 80000), 'password' => 'SCHMOOPIIE'];