1
|
|
|
<?php |
2
|
|
|
namespace App\Gitter\Extensions\Middleware; |
3
|
|
|
|
4
|
|
|
use App\Message; |
5
|
|
|
use App\Room; |
6
|
|
|
use Gitter\Client; |
7
|
|
|
use Gitter\Models\Room as GitterRoom; |
8
|
|
|
use Illuminate\Contracts\Container\Container; |
9
|
|
|
use App\Gitter\Extensions\ExtensionInterface; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Class MiddlewaresExtension |
13
|
|
|
* @package App\Gitter\Middleware |
14
|
|
|
*/ |
15
|
|
|
class MiddlewaresExtension implements ExtensionInterface |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @var array |
19
|
|
|
*/ |
20
|
|
|
protected $items = []; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var Container |
24
|
|
|
*/ |
25
|
|
|
protected $container; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @var GitterRoom |
29
|
|
|
*/ |
30
|
|
|
protected $room; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @var Room |
34
|
|
|
*/ |
35
|
|
|
protected $roomObject; |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Repository constructor. |
39
|
|
|
* @param GitterRoom $room |
40
|
|
|
* @param Container $container |
41
|
|
|
*/ |
42
|
|
|
public function __construct(GitterRoom $room, Container $container) |
43
|
|
|
{ |
44
|
|
|
$this->room = $room; |
45
|
|
|
$this->roomObject = Room::make($this->room); |
46
|
|
|
$this->container = $container; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param $middleware |
51
|
|
|
* @return $this |
52
|
|
|
*/ |
53
|
|
|
public function register(string $middleware) |
54
|
|
|
{ |
55
|
|
|
$this->items[] = $this->container->make($middleware, [ |
56
|
|
|
'room' => $this->roomObject, |
57
|
|
|
'gitter' => $this->room |
58
|
|
|
]); |
59
|
|
|
return $this; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @param Message $message |
64
|
|
|
* @return mixed |
65
|
|
|
*/ |
66
|
|
|
public function fire(Message $message) |
67
|
|
|
{ |
68
|
|
|
if (count($this->items)) { |
69
|
|
|
$response = new Response($this->fireMiddleware(0, $message)); |
70
|
|
|
|
71
|
|
|
if (!$response->isEmpty()) { |
72
|
|
|
$content = $response->getContent(); |
73
|
|
|
|
74
|
|
|
$this->room->sendMessage($content); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
/** |
80
|
|
|
* @param int $number |
81
|
|
|
* @param Message $message |
82
|
|
|
* @return mixed |
83
|
|
|
*/ |
84
|
|
|
protected function fireMiddleware(int $number, Message $message) |
85
|
|
|
{ |
86
|
|
|
if (!array_key_exists($number, $this->items)) { |
87
|
|
|
return new Response; |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
$middleware = $this->items[$number]; |
91
|
|
|
|
92
|
|
|
return $this->container->call([$middleware, 'handle'], [ |
93
|
|
|
'message' => $message, |
94
|
|
|
'next' => function(Message $message) use ($number) { |
95
|
|
|
$result = $this->fireMiddleware(++$number, $message); |
96
|
|
|
|
97
|
|
|
if (!($result instanceof Response)) { |
98
|
|
|
return new Response($result); |
99
|
|
|
} |
100
|
|
|
|
101
|
|
|
return $result; |
102
|
|
|
} |
103
|
|
|
]); |
104
|
|
|
} |
105
|
|
|
} |
106
|
|
|
|