Skip to content

Instantly share code, notes, and snippets.

@trizz
Created March 14, 2016 14:53
Show Gist options
  • Save trizz/73dfdb145eb355a63709 to your computer and use it in GitHub Desktop.
Save trizz/73dfdb145eb355a63709 to your computer and use it in GitHub Desktop.
<?php
namespace App;
use Exception;
use MessagePack\Packer;
use Redis;
class SocketIO
{
private $redis;
private $rooms;
private $nsp;
private $flags;
private $uid;
private $key;
/**
* @param bool|array $redis Redis-Client or Array of options
* @param array $opts Array of options
*
* @throws Exception
*/
function __construct($redis = false, $opts = [])
{
if (is_array($redis)) {
$opts = $redis;
$redis = false;
}
$opts = array_merge(["host" => "localhost", "port" => 6379], $opts);
if (!$redis) {
// When no Redis is passed, access the facade.
$redis = new Redis();
}
$this->redis = $redis;
if (!is_callable([$this->redis, "publish"])) {
throw new \Exception(
"The Redis client provided is invalid. The client needs to implement the publish method. Try using the default client."
);
}
$this->rooms = [];
$this->flags = [];
$this->nsp = "/";
$this->key = isset($opts["key"]) ? $opts["key"] : "socket.io";
$this->uid = uniqid();
}
/**
* @param $key string New key (Channel-Name beginning, default: socket.io)
*/
function setKey($key)
{
$this->key = $key;
}
/**
* @return string Current key (Channel-Name beginning, default: socket.io)
*/
function getKey()
{
return $this->key;
}
/**
* @param $room string Room-Name
*
* @return $this Emitter
*/
function in($room)
{
if (!in_array($room, $this->rooms)) {
array_push($this->rooms, $room);
}
return $this;
}
/**
* @param $room string Room-Name
*
* @return Emitter
*/
public function to($room)
{
return $this->in($room);
}
/**
* @param $nsp string Namespace
*
* @return $this Emitter
*/
public function of($nsp)
{
$this->nsp = $nsp;
return $this;
}
/**
* @param $event string Name of event
* @param $data array Data
*/
public function emit($event, $data)
{
$packer = new Packer();
$packet = [];
$packet["type"] = 2;
$packet["data"] = [];
$packet["data"][0] = $event;
$packet["data"][1] = $data;
$packet["nsp"] = $this->nsp;
$this->redis->publish(
$this->key."#".$this->nsp."#",
$packer->pack(
[
uniqid(),
$packet,
[
"rooms" => $this->rooms,
"flags" => $this->flags
]
]
)
);
$this->rooms = [];
$this->flags = [];
$this->nsp = "/";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment