-
Notifications
You must be signed in to change notification settings - Fork 0
/
BufferedQueue.php
120 lines (101 loc) · 2.6 KB
/
BufferedQueue.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<?php
/**
* Created by MD. Mahmud Ur Rahman <[email protected]>.
*/
namespace Mahmud\BufferedQueue;
class BufferedQueue {
/**
* @var array BufferedQueue[]
*/
protected static $instances = [];
/**
* @var array
*/
protected $all_data;
/**
* @var integer
*/
protected $max_items_in_queue;
/**
* @var \Closure|HandlerContract
*/
protected $handler;
/**
* BufferedQueue constructor.
*
* @param $handler \Closure|HandlerContract
* @param $max_items_in_queue
*/
public function __construct($handler, $max_items_in_queue) {
$this->all_data = [];
$this->max_items_in_queue = $max_items_in_queue;
$this->handler = $handler;
}
public static function make($key, $handler, $max_items_in_queue) {
if (array_key_exists($key, self::$instances)) {
return self::$instances[$key];
}
$instance = new self($handler, $max_items_in_queue);
self::$instances[$key] = $instance;
return $instance;
}
/**
* @param $data
*
* @return $this
* @throws \Exception
*/
public function push($data) {
$this->all_data[] = $data;
if (count($this->all_data) >= $this->max_items_in_queue) {
$this->run();
}
return $this;
}
/**
* @return $this
* @throws \Exception
*/
public function run() {
if (count($this->all_data) > 0) {
try {
$this->callHandler();
} catch (\Exception $e) {
throw $e;
} finally {
$this->all_data = [];
}
}
return $this;
}
/**
* @return mixed
* @throws \Exception
*/
protected function callHandler() {
if ($this->handler instanceof \Closure) {
return call_user_func($this->handler, $this->all_data);
}
if ($this->handler instanceof HandlerContract) {
return $this->handler->handle($this->all_data);
}
throw new \Exception("Handler is not supported. Must be a valid closure or instance of " . HandlerContract::class);
}
public function getItems() {
return $this->all_data;
}
/**
* @return $this
* @throws \Exception
*/
public function finish() {
$this->run();
return $this;
}
/**
* @throws \Exception
*/
public function __destruct() {
$this->run();
}
}