This repository has been archived by the owner on Dec 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SwitchBoard.php
105 lines (86 loc) · 1.91 KB
/
SwitchBoard.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
namespace Flownode\Switchboard;
use Flownode\Switchboard\Channels;
use Flownode\Switchboard\Response;
/**
*
*/
class Switchboard
{
/**
*
* @var \SwitchBoard\SwitchBoard
*/
private static $_instance = null;
/**
* Collection of Channel
*
* @var \SwitchBoard\Channels
*/
private $channels;
/**
* Register a callback function to a channel
*
* @param string $channel Channel name
* @param function | closure | SwitchBoardResponseInterface $callback
*/
public function register($channel, $callback)
{
$this->channels[$channel] = $callback;
}
/**
* Return the unique SwitchBoard instance
*
*
* @return \self
*/
public static function get()
{
if(null == self::$_instance)
{
return new self();
}
return self::$_instance;
}
/**
* Shortcut for resolving all channels from request
*
* @param array $request
* @return string
*/
public function connect(array $request)
{
$response = new Response();
foreach($request as $channel => $data)
{
$response->add($this->resolve($channel, $data));
}
return $response;
}
/**
* Execute a callback for a specific channel
*
* @param string $channel
* @param array $data
* @return array
*/
public function resolve($channel, $data)
{
$callback = $this->channels[$channel];
if($callback instanceof \Closure) {
$response = $callback($this, $data);
} else if (is_array($callback)) {
$response = call_user_func_array(array($callback[0], $callback[1]), array($this, $data));
} else {
$response = array();
}
return $response;
}
/**
* Contructor shoul'nt be called that way, for instance
*/
private function __constuct()
{
$this->channels = new Channels();
}
}