class-queue.php
1.97 KB
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
121
122
123
124
<?php
class WPF_CRM_Queue {
/**
* Holds the current active CRM object
*/
private $crm;
/**
* Buffer for queued API calls
*/
private $buffer;
public function __construct($crm) {
$this->crm = $crm;
$this->buffer = array();
add_action( 'shutdown', array( $this, 'shutdown' ) );
}
/**
* Passes get requests to the base CRM class
*
* @access public
* @return void
*/
public function __get($name) {
return $this->crm->$name;
}
/**
* Routes queue-able API calls to the buffer
*
* @access public
* @return void
*/
public function __call( $method, $args ) {
// Queue sending data
if( $method == 'apply_tags' || $method == 'remove_tags' || $method == 'update_contact' ) {
$this->add_to_buffer( $method, $args );
return true;
} else {
$result = call_user_func_array(array($this->crm, $method), $args);
return $result;
}
}
/**
* Adds API requests to the API buffer
*
* @access private
* @return void
*/
private function add_to_buffer( $method, $args ) {
if($method == 'apply_tags' || $method == 'remove_tags') {
$cid = $args[1];
} else {
$cid = $args[0];
}
if(!isset($this->buffer[$method])) {
$this->buffer[$method] = array( $cid => $args );
} elseif(!isset($this->buffer[$method][$cid])) {
$this->buffer[$method][$cid] = $args;
} else {
if($method == 'apply_tags' || $method == 'remove_tags') {
$this->buffer[$method][$cid][0] = array_unique(array_merge($this->buffer[$method][$cid][0], $args[0]));
} else {
$this->buffer[$method][$cid][1] = array_merge($this->buffer[$method][$cid][1], $args[1]);
}
}
}
/**
* Executes the queued API requests on PHP shutdown
*
* @access public
* @return void
*/
public function shutdown() {
if(empty($this->buffer))
return;
foreach($this->buffer as $method => $contacts) {
foreach($contacts as $cid => $args) {
call_user_func_array(array($this->crm, $method), $args);
}
}
}
}