public function write(string $bytes) : Awaitable
{
if ($bytes === '') {
if (!\is_resource($this->socket)) {
return new Failure(new StreamClosedException('Socket resource unavailable'));
}
return new Success(0);
}
$len = \strlen($bytes);
if (!$this->writerEnabled) {
try {
$bytes = $this->writeBytes($bytes);
} catch (\Throwable $e) {
return new Failure($e);
}
if ($bytes === '') {
return new Success($len);
}
$this->writerEnabled = true;
if ($this->pendingWrites === null) {
$this->pendingWrites = new \SplQueue();
}
if ($this->writeWatcher === null) {
$this->writeWatcher = Loop::onWritable($this->socket, $this->createWriteWatcher());
} else {
try {
Loop::enable($this->writeWatcher);
} catch (InvalidWatcherException $e) {
$this->writeWatcher = Loop::onWritable($this->socket, $this->createWriteWatcher());
}
}
if (!$this->writerReferenced) {
Loop::unreference($this->writeWatcher);
}
}
$this->pendingWrites->enqueue($write = new PendingWrite($bytes, $len, function () {
foreach ($this->pendingWrites as $write) {
if (!$write->disabled) {
return;
}
}
$this->writerEnabled = false;
Loop::disable($this->writeWatcher);
}));
return $write;
}