Skip to content

Commit

Permalink
Merge pull request #5 from danilopolani/feature/execute-on-connect
Browse files Browse the repository at this point in the history
Allow a callback to be executed on connection
  • Loading branch information
ghostzero authored Apr 21, 2021
2 parents 4bba3ba + 7a25363 commit 35467a7
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
17 changes: 13 additions & 4 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,15 @@ 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();
$dns = $dnsResolverFactory->createCached($this->options->getNameserver(), $this->loop);
$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 = [];
Expand All @@ -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 () {
Expand All @@ -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();
Expand Down
5 changes: 5 additions & 0 deletions src/ClientOptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'];
Expand Down

0 comments on commit 35467a7

Please sign in to comment.