1
0
mirror of https://github.com/danog/postgres.git synced 2024-11-30 04:29:12 +01:00
postgres/lib/Listener.php

88 lines
2.2 KiB
PHP
Raw Normal View History

2016-12-30 06:21:17 +01:00
<?php
2016-09-19 18:12:32 +02:00
namespace Amp\Postgres;
use Amp\Iterator;
use Amp\Promise;
2016-09-19 18:12:32 +02:00
2017-05-16 06:14:02 +02:00
class Listener implements Iterator, Operation {
/** @var \Amp\Iterator */
private $iterator;
2016-09-19 18:12:32 +02:00
/** @var string */
private $channel;
2017-05-16 06:28:37 +02:00
2016-09-19 18:12:32 +02:00
/** @var callable */
private $unlisten;
2017-05-16 06:28:37 +02:00
/** @var \Amp\Postgres\Internal\ReferenceQueue */
private $queue;
2016-09-19 18:12:32 +02:00
/**
2017-05-16 06:14:02 +02:00
* @param \Amp\Iterator $iterator Iterator emitting notificatons on the channel.
2016-09-19 18:12:32 +02:00
* @param string $channel Channel name.
2017-06-05 05:15:32 +02:00
* @param callable(string $channel): \Amp\Promise $unlisten Function invoked to unlisten from the channel.
2016-09-19 18:12:32 +02:00
*/
2017-05-16 06:14:02 +02:00
public function __construct(Iterator $iterator, string $channel, callable $unlisten) {
$this->iterator = $iterator;
2016-09-19 18:12:32 +02:00
$this->channel = $channel;
$this->unlisten = $unlisten;
$this->queue = new Internal\ReferenceQueue;
2016-09-19 18:12:32 +02:00
}
2017-05-16 06:14:02 +02:00
public function __destruct() {
if ($this->unlisten) {
$this->unlisten(); // Invokes $this->queue->complete().
}
}
/**
* {@inheritdoc}
*/
public function onDestruct(callable $onComplete) {
$this->queue->onDestruct($onComplete);
}
2017-05-16 06:14:02 +02:00
/**
* {@inheritdoc}
*/
public function advance(): Promise {
return $this->iterator->advance();
}
/**
* {@inheritdoc}
2017-05-26 05:47:49 +02:00
*
* @return \Amp\Postgres\Notification
2017-05-16 06:14:02 +02:00
*/
2017-05-26 05:47:49 +02:00
public function getCurrent(): Notification {
2017-05-16 06:14:02 +02:00
return $this->iterator->getCurrent();
}
/**
* @return string Channel name.
*/
public function getChannel(): string {
return $this->channel;
}
2017-05-16 06:28:37 +02:00
2016-09-19 18:12:32 +02:00
/**
2017-06-05 05:15:32 +02:00
* Unlistens from the channel. No more values will be emitted from this listener.
2016-09-19 18:12:32 +02:00
*
* @return \Amp\Promise<\Amp\Postgres\CommandResult>
*
* @throws \Error If this method was previously invoked.
2016-09-19 18:12:32 +02:00
*/
2016-11-15 18:06:21 +01:00
public function unlisten(): Promise {
if (!$this->unlisten) {
throw new \Error("Already unlistened on this channel");
}
/** @var \Amp\Promise $promise */
2016-11-15 18:06:21 +01:00
$promise = ($this->unlisten)($this->channel);
$this->unlisten = null;
$promise->onResolve([$this->queue, "unreference"]);
2016-11-15 18:06:21 +01:00
return $promise;
2016-09-19 18:12:32 +02:00
}
}