appwrite/src/Appwrite/Event/Realtime.php

137 lines
3 KiB
PHP
Raw Normal View History

2021-02-24 12:19:46 +00:00
<?php
namespace Appwrite\Event;
use Appwrite\Database\Document;
use Utopia\App;
class Realtime
{
/**
* @var string
*/
protected $event = '';
/**
* @var array
*/
protected $channels = [];
/**
* @var Document
*/
protected $payload;
/**
* Event constructor.
*
* @param string $event
* @param array $payload
*/
public function __construct(string $event, array $payload)
{
$this->event = $event;
$this->payload = new Document($payload);
}
/**
* @param string $event
* return $this
*/
public function setEvent(string $event): self
{
$this->event = $event;
return $this;
}
/**
* @return string
*/
public function getEvent(): string
{
return $this->event;
}
/**
* @param array $payload
* return $this
*/
public function setPayload(array $payload): self
{
$this->payload = new Document($payload);
return $this;
}
/**
* @return Document
*/
public function getPayload(): Document
{
return $this->payload;
}
/**
* Populate channels array based on the event name and payload.
*
* @return void
*/
private function prepareChannels(): void
{
switch (true) {
case strpos($this->event, 'account.') === 0:
$this->channels[] = 'account.' . $this->payload->getId();
break;
case strpos($this->event, 'database.collections.') === 0:
$this->channels[] = 'collections';
$this->channels[] = 'collections.' . $this->payload->getId();
break;
case strpos($this->event, 'database.documents.') === 0:
$this->channels[] = 'documents';
$this->channels[] = 'collections.' . $this->payload->getAttribute('$collection') . '.documents';
$this->channels[] = 'documents.' . $this->payload->getId();
break;
case strpos($this->event, 'storage.') === 0:
$this->channels[] = 'files';
$this->channels[] = 'files.' . $this->payload->getId();
break;
}
}
/**
* Execute Event.
*
* @return void
*/
public function trigger(): void
{
$this->prepareChannels();
if (empty($this->channels)) return;
$redis = new \Redis();
$redis->connect(App::getEnv('_APP_REDIS_HOST', ''), App::getEnv('_APP_REDIS_PORT', ''));
$redis->publish('realtime', json_encode([
'channels' => $this->channels,
'data' => [
'event' => $this->event,
'timestamp' => time(),
'payload' => $this->payload
]
]));
$this->reset();
}
public function reset(): self
{
$this->event = '';
$this->payload = $this->channels = [];
return $this;
}
}