/
QueryLogger.php
executable file
·97 lines (89 loc) · 2.25 KB
/
QueryLogger.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
<?php
/**
* Query Logger
*
* @file RedBean/Plugin/QueryLogger.php
* @description Query logger, can be attached to an observer that
* signals the sql_exec event.
* @author Gabor de Mooij and the RedBeanPHP Community
* @license BSD/GPLv2
*
*
* (c) copyright G.J.G.T. (Gabor) de Mooij and the RedBeanPHP Community.
* This source file is subject to the BSD/GPLv2 License that is bundled
* with this source code in the file license.txt.
*/
class RedBean_Plugin_QueryLogger implements RedBean_Observer, RedBean_Plugin {
/**
* @var array
* contains log messages
*/
protected $logs = array();
/**
* Creates a new instance of the Query Logger and attaches
* this logger to the adapter.
*
* @static
* @param RedBean_Observable $adapter the adapter you want to attach to
*
* @return RedBean_Plugin_QueryLogger $querylogger instance of the Query Logger
*/
public static function getInstanceAndAttach( RedBean_Observable $adapter ) {
$queryLog = new RedBean_Plugin_QueryLogger;
$adapter->addEventListener( 'sql_exec', $queryLog );
return $queryLog;
}
/**
* Singleton pattern
* Constructor - private
*/
private function __construct(){}
/**
* Implementation of the onEvent() method for Observer interface.
* If a query gets executed this method gets invoked because the
* adapter will send a signal to the attached logger.
*
* @param string $eventName ID of the event (name)
* @param RedBean_DBAdapter $adapter adapter that sends the signal
*
* @return void
*/
public function onEvent( $eventName, $adapter ) {
if ($eventName=='sql_exec') {
$this->logs[] = $adapter->getSQL();
}
}
/**
* Searches the logs for the given word and returns the entries found in
* the log container.
*
* @param string $word word to look for
*
* @return array $entries entries that contain the keyword
*/
public function grep( $word ) {
$found = array();
foreach($this->logs as $log) {
if (strpos($log,$word)!==false) {
$found[] = $log;
}
}
return $found;
}
/**
* Returns all the logs.
*
* @return array $logs logs
*/
public function getLogs() {
return $this->logs;
}
/**
* Clears the logs.
*
* @return void
*/
public function clear() {
$this->logs = array();
}
}