forked from liftiuminc/liftium
/
EventRecorder.php
106 lines (91 loc) · 2.43 KB
/
EventRecorder.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
<?php
/* Store events in a temporary, high performance store, to be aggregated later.
* Currently using memcache for this later. Maybe someday the message queue?
*
* Example usage:
* EventRecorder::record(array('Ad Delivered', 'AdBrite', 'US'), "minute");
*/
class EventRecorder {
static public function record($event, $rotation = "hour", $timeout = null){
$cache = LiftiumCache::getInstance();
if (!is_array($event)){
trigger_error('$event is not an array for EventRecorder::record', E_USER_WARNING);
return false;
}
$key = self::serializeKey($event, $rotation);
$ret = $cache->increment($key);
if (empty($ret)){
// Increment does not create the key if it does not exist. Retarded.
if ($timeout === null){
$timeout = self::getTimeOut($rotation);
}
$cache->set($key, 0, 0, $timeout);
$ret = $cache->increment($key);
}
return $ret;
}
static public function serializeKey($event, $rotation = "hour", $time = null){
$key = "";
foreach ($event as $e){
$key .= urlencode($e) . ':';
}
if (is_null($time)){
$time = time();
}
return $key . self::getTimeFloor($rotation, $time);
}
public function unserializeKey($key){
$pieces = explode(':', $key);
if (empty($pieces)){
return false;
}
$time = array_pop($pieces);
$events = array();
foreach ($pieces as $piece){
$events[] = urldecode($piece);
}
$out = array(
'events'=> $events,
'time' => $time,
'rotation' => self::getRotation($time)
);
}
static public function getTimeFloor($rotation, $time){
switch($rotation){
case 'minute': return date('Ymd_Hi00', $time);
case 'hour': return date('Ymd_H', $time);
case 'day': return date('Ymd', $time);
default: return null;
}
}
public function getRotation($time){
switch(strlen($time)){
case 15: return 'minute';
case 11: return 'hour';
case 8: return 'day';
default: return null;
}
}
public static function getTimeOut($rotation){
switch($rotation){
case 'minute': return 360;
case 'hour': return 86400;
case 'day': return 86400 * 7;
default: return 300;
}
}
public function getEventsByType($eventType){
// Pull a list of keys from memcached
$cache = LiftiumCache::getInstance();
$keylist = getCacheKeyList();
$out = array();
for ($i = 0 ; $i<sizeof($keylist); $i++){
$data = self::unserializeKey($keylist[$i]);
if ($data['events'][0] == $mainevent){
$out = $data;
}
}
return $out;
}
}
?>