Completed
Push — master ( 7af328...5e661d )
by Jacob
11:47 queued 13s
created
tests/helpers/LoggingPdo.php 1 patch
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -6,5 +6,5 @@
 block discarded – undo
6 6
 
7 7
 class LoggingPdo extends PDO
8 8
 {
9
-    public $queries = array();
9
+	public $queries = array();
10 10
 }
Please login to merge, or discard this patch.
tests/bootstrap.php 1 patch
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@
 block discarded – undo
1 1
 <?php
2 2
 
3
-require_once __DIR__ . '/../vendor/autoload.php';
4
-require_once __DIR__ . '/helpers/function-overrides.php';
5
-require_once __DIR__ . '/helpers/LoggingPdo.php';
3
+require_once __DIR__.'/../vendor/autoload.php';
4
+require_once __DIR__.'/helpers/function-overrides.php';
5
+require_once __DIR__.'/helpers/LoggingPdo.php';
Please login to merge, or discard this patch.
src/PhpQuickProfiler.php 1 patch
Indentation   +190 added lines, -190 removed lines patch added patch discarded remove patch
@@ -17,194 +17,194 @@
 block discarded – undo
17 17
 class PhpQuickProfiler
18 18
 {
19 19
 
20
-    /** @var  double */
21
-    protected $startTime;
22
-
23
-    /** @var  Console */
24
-    protected $console;
25
-
26
-    /** @var  Display */
27
-    protected $display;
28
-
29
-    /** @var  array */
30
-    protected $profiledQueries = array();
31
-
32
-    /**
33
-     * @param double $startTime
34
-     */
35
-    public function __construct($startTime = null)
36
-    {
37
-        if (is_null($startTime)) {
38
-            $startTime = microtime(true);
39
-        }
40
-        $this->startTime = $startTime;
41
-    }
42
-
43
-    /**
44
-     * @param Console $console
45
-     */
46
-    public function setConsole(Console $console)
47
-    {
48
-        $this->console = $console;
49
-    }
50
-
51
-    /**
52
-     * @param Display $display
53
-     */
54
-    public function setDisplay(Display $display)
55
-    {
56
-        $this->display = $display;
57
-    }
58
-
59
-    /**
60
-     * Get data about files loaded for the application to current point
61
-     *
62
-     * @returns array
63
-     */
64
-    public function gatherFileData()
65
-    {
66
-        $files = get_included_files();
67
-        $data = array();
68
-        foreach ($files as $file) {
69
-            array_push($data, array(
70
-                'name' => $file,
71
-                'size' => filesize($file)
72
-            ));
73
-        }
74
-        return $data;
75
-    }
76
-
77
-    /**
78
-     * Get data about memory usage of the application
79
-     *
80
-     * @returns array
81
-     */
82
-    public function gatherMemoryData()
83
-    {
84
-        $usedMemory = memory_get_peak_usage();
85
-        $allowedMemory = ini_get('memory_limit');
86
-        return array(
87
-            'used'    => $usedMemory,
88
-            'allowed' => $allowedMemory
89
-        );
90
-    }
91
-
92
-    /**
93
-     * @param array $profiledQueries
94
-     */
95
-    public function setProfiledQueries(array $profiledQueries)
96
-    {
97
-        $this->profiledQueries = $profiledQueries;
98
-    }
99
-
100
-    /**
101
-     * Get data about sql usage of the application
102
-     *
103
-     * @param object $dbConnection
104
-     * @returns array
105
-     */
106
-    public function gatherQueryData($dbConnection = null)
107
-    {
108
-        if (is_null($dbConnection)) {
109
-            return array();
110
-        }
111
-
112
-        if (empty($this->profiledQueries) && property_exists($dbConnection, 'queries')) {
113
-            $this->setProfiledQueries($dbConnection->queries);
114
-        }
115
-
116
-        $data = array();
117
-        foreach ($this->profiledQueries as $query) {
118
-            array_push($data, array(
119
-                'sql'     => $query['sql'],
120
-                'explain' => $this->explainQuery($dbConnection, $query['sql'], $query['parameters']),
121
-                'time'    => $query['time']
122
-            ));
123
-        }
124
-        return $data;
125
-    }
126
-
127
-    /**
128
-     * Attempts to explain a query
129
-     *
130
-     * @param object $dbConnection
131
-     * @param string $query
132
-     * @param array  $parameters
133
-     * @throws Exception
134
-     * @return array
135
-     */
136
-    protected function explainQuery($dbConnection, $query, $parameters = array())
137
-    {
138
-        $driver = $dbConnection->getAttribute(\PDO::ATTR_DRIVER_NAME);
139
-        $query = $this->getExplainQuery($query, $driver);
140
-        $statement = $dbConnection->prepare($query);
141
-        if ($statement === false) {
142
-            throw new Exception('Invalid query passed to explainQuery method');
143
-        }
144
-        $statement->execute($parameters);
145
-        $result = $statement->fetch(\PDO::FETCH_ASSOC);
146
-        if ($result === false) {
147
-            throw new Exception('Query could not be explained with given parameters');
148
-        }
149
-        return $result;
150
-    }
151
-
152
-    /**
153
-     * Attempts to figure out what kind of explain query format the db wants
154
-     *
155
-     * @param string $query
156
-     * @param string $driver
157
-     * @throws Exception
158
-     * @return string
159
-     */
160
-    protected function getExplainQuery($query, $driver)
161
-    {
162
-        if ($driver == 'mysql') {
163
-            return "EXPLAIN {$query}";
164
-        } elseif ($driver == 'sqlite') {
165
-            return "EXPLAIN QUERY PLAN {$query}";
166
-        }
167
-        throw new Exception('Could not process db driver');
168
-    }
169
-
170
-    /**
171
-     * Get data about speed of the application
172
-     *
173
-     * @returns array
174
-     */
175
-    public function gatherSpeedData()
176
-    {
177
-        $elapsedTime = microtime(true) - $this->startTime;
178
-        $elapsedTime = round($elapsedTime, 3);
179
-        $allowedTime = ini_get('max_execution_time');
180
-        return array(
181
-            'elapsed' => $elapsedTime,
182
-            'allowed' => $allowedTime
183
-        );
184
-    }
185
-
186
-    /**
187
-     * Triggers end display of the profiling data
188
-     *
189
-     * @param object $dbConnection
190
-     * @throws Exception
191
-     */
192
-    public function display($dbConnection = null)
193
-    {
194
-        if (!isset($this->display)) {
195
-            throw new Exception('Display object has not been injected into Profiler');
196
-        }
197
-        if (!isset($this->console)) {
198
-            throw new Exception('Console object has not been injected into Profiler');
199
-        }
200
-
201
-        $this->display->setStartTime($this->startTime);
202
-        $this->display->setConsole($this->console);
203
-        $this->display->setFileData($this->gatherFileData());
204
-        $this->display->setMemoryData($this->gatherMemoryData());
205
-        $this->display->setQueryData($this->gatherQueryData($dbConnection));
206
-        $this->display->setSpeedData($this->gatherSpeedData());
207
-
208
-        $this->display->__invoke();
209
-    }
20
+	/** @var  double */
21
+	protected $startTime;
22
+
23
+	/** @var  Console */
24
+	protected $console;
25
+
26
+	/** @var  Display */
27
+	protected $display;
28
+
29
+	/** @var  array */
30
+	protected $profiledQueries = array();
31
+
32
+	/**
33
+	 * @param double $startTime
34
+	 */
35
+	public function __construct($startTime = null)
36
+	{
37
+		if (is_null($startTime)) {
38
+			$startTime = microtime(true);
39
+		}
40
+		$this->startTime = $startTime;
41
+	}
42
+
43
+	/**
44
+	 * @param Console $console
45
+	 */
46
+	public function setConsole(Console $console)
47
+	{
48
+		$this->console = $console;
49
+	}
50
+
51
+	/**
52
+	 * @param Display $display
53
+	 */
54
+	public function setDisplay(Display $display)
55
+	{
56
+		$this->display = $display;
57
+	}
58
+
59
+	/**
60
+	 * Get data about files loaded for the application to current point
61
+	 *
62
+	 * @returns array
63
+	 */
64
+	public function gatherFileData()
65
+	{
66
+		$files = get_included_files();
67
+		$data = array();
68
+		foreach ($files as $file) {
69
+			array_push($data, array(
70
+				'name' => $file,
71
+				'size' => filesize($file)
72
+			));
73
+		}
74
+		return $data;
75
+	}
76
+
77
+	/**
78
+	 * Get data about memory usage of the application
79
+	 *
80
+	 * @returns array
81
+	 */
82
+	public function gatherMemoryData()
83
+	{
84
+		$usedMemory = memory_get_peak_usage();
85
+		$allowedMemory = ini_get('memory_limit');
86
+		return array(
87
+			'used'    => $usedMemory,
88
+			'allowed' => $allowedMemory
89
+		);
90
+	}
91
+
92
+	/**
93
+	 * @param array $profiledQueries
94
+	 */
95
+	public function setProfiledQueries(array $profiledQueries)
96
+	{
97
+		$this->profiledQueries = $profiledQueries;
98
+	}
99
+
100
+	/**
101
+	 * Get data about sql usage of the application
102
+	 *
103
+	 * @param object $dbConnection
104
+	 * @returns array
105
+	 */
106
+	public function gatherQueryData($dbConnection = null)
107
+	{
108
+		if (is_null($dbConnection)) {
109
+			return array();
110
+		}
111
+
112
+		if (empty($this->profiledQueries) && property_exists($dbConnection, 'queries')) {
113
+			$this->setProfiledQueries($dbConnection->queries);
114
+		}
115
+
116
+		$data = array();
117
+		foreach ($this->profiledQueries as $query) {
118
+			array_push($data, array(
119
+				'sql'     => $query['sql'],
120
+				'explain' => $this->explainQuery($dbConnection, $query['sql'], $query['parameters']),
121
+				'time'    => $query['time']
122
+			));
123
+		}
124
+		return $data;
125
+	}
126
+
127
+	/**
128
+	 * Attempts to explain a query
129
+	 *
130
+	 * @param object $dbConnection
131
+	 * @param string $query
132
+	 * @param array  $parameters
133
+	 * @throws Exception
134
+	 * @return array
135
+	 */
136
+	protected function explainQuery($dbConnection, $query, $parameters = array())
137
+	{
138
+		$driver = $dbConnection->getAttribute(\PDO::ATTR_DRIVER_NAME);
139
+		$query = $this->getExplainQuery($query, $driver);
140
+		$statement = $dbConnection->prepare($query);
141
+		if ($statement === false) {
142
+			throw new Exception('Invalid query passed to explainQuery method');
143
+		}
144
+		$statement->execute($parameters);
145
+		$result = $statement->fetch(\PDO::FETCH_ASSOC);
146
+		if ($result === false) {
147
+			throw new Exception('Query could not be explained with given parameters');
148
+		}
149
+		return $result;
150
+	}
151
+
152
+	/**
153
+	 * Attempts to figure out what kind of explain query format the db wants
154
+	 *
155
+	 * @param string $query
156
+	 * @param string $driver
157
+	 * @throws Exception
158
+	 * @return string
159
+	 */
160
+	protected function getExplainQuery($query, $driver)
161
+	{
162
+		if ($driver == 'mysql') {
163
+			return "EXPLAIN {$query}";
164
+		} elseif ($driver == 'sqlite') {
165
+			return "EXPLAIN QUERY PLAN {$query}";
166
+		}
167
+		throw new Exception('Could not process db driver');
168
+	}
169
+
170
+	/**
171
+	 * Get data about speed of the application
172
+	 *
173
+	 * @returns array
174
+	 */
175
+	public function gatherSpeedData()
176
+	{
177
+		$elapsedTime = microtime(true) - $this->startTime;
178
+		$elapsedTime = round($elapsedTime, 3);
179
+		$allowedTime = ini_get('max_execution_time');
180
+		return array(
181
+			'elapsed' => $elapsedTime,
182
+			'allowed' => $allowedTime
183
+		);
184
+	}
185
+
186
+	/**
187
+	 * Triggers end display of the profiling data
188
+	 *
189
+	 * @param object $dbConnection
190
+	 * @throws Exception
191
+	 */
192
+	public function display($dbConnection = null)
193
+	{
194
+		if (!isset($this->display)) {
195
+			throw new Exception('Display object has not been injected into Profiler');
196
+		}
197
+		if (!isset($this->console)) {
198
+			throw new Exception('Console object has not been injected into Profiler');
199
+		}
200
+
201
+		$this->display->setStartTime($this->startTime);
202
+		$this->display->setConsole($this->console);
203
+		$this->display->setFileData($this->gatherFileData());
204
+		$this->display->setMemoryData($this->gatherMemoryData());
205
+		$this->display->setQueryData($this->gatherQueryData($dbConnection));
206
+		$this->display->setSpeedData($this->gatherSpeedData());
207
+
208
+		$this->display->__invoke();
209
+	}
210 210
 }
Please login to merge, or discard this patch.
tests/unit/PhpQuickProfilerTest.php 1 patch
Indentation   +321 added lines, -321 removed lines patch added patch discarded remove patch
@@ -8,19 +8,19 @@  discard block
 block discarded – undo
8 8
 class PhpQuickProfilerTest extends PHPUnit_Framework_TestCase
9 9
 {
10 10
 
11
-    protected static $dbConnection;
11
+	protected static $dbConnection;
12 12
 
13
-    public static function setUpBeforeClass()
14
-    {
15
-        self::$dbConnection = new LoggingPdo('sqlite::memory:');
16
-        $createTable = "
13
+	public static function setUpBeforeClass()
14
+	{
15
+		self::$dbConnection = new LoggingPdo('sqlite::memory:');
16
+		$createTable = "
17 17
             CREATE TABLE IF NOT EXISTS `testing` (
18 18
                 `id` integer PRIMARY KEY AUTOINCREMENT,
19 19
                 `title` varchar(60) NOT NULL
20 20
             );";
21
-        self::$dbConnection->exec($createTable);
21
+		self::$dbConnection->exec($createTable);
22 22
 
23
-        $hydrateTable = "
23
+		$hydrateTable = "
24 24
             INSERT INTO `testing`
25 25
                 (`title`)
26 26
             VALUES
@@ -28,318 +28,318 @@  discard block
 block discarded – undo
28 28
                 ('beta'),
29 29
                 ('charlie'),
30 30
                 ('delta');";
31
-        self::$dbConnection->exec($hydrateTable);
32
-    }
33
-
34
-    public function testConstruct()
35
-    {
36
-        $startTime = microtime(true);
37
-
38
-        $profiler = new PhpQuickProfiler();
39
-        $this->assertAttributeEquals($startTime, 'startTime', $profiler);
40
-
41
-        $profiler = new PhpQuickProfiler($startTime);
42
-        $this->assertAttributeEquals($startTime, 'startTime', $profiler);
43
-    }
44
-
45
-    public function testSetConsole()
46
-    {
47
-        $console = new Console();
48
-        $profiler = new PhpQuickProfiler();
49
-        $profiler->setConsole($console);
50
-
51
-        $this->assertAttributeSame($console, 'console', $profiler);
52
-    }
53
-
54
-    public function testSetDisplay()
55
-    {
56
-        $display = new Display();
57
-        $profiler = new PhpQuickProfiler();
58
-        $profiler->setDisplay($display);
59
-
60
-        $this->assertAttributeSame($display, 'display', $profiler);
61
-    }
62
-
63
-    public function testGatherFileData()
64
-    {
65
-        $files = get_included_files();
66
-        $profiler = new PhpQuickProfiler();
67
-        $gatheredFileData = $profiler->gatherFileData();
68
-
69
-        $this->assertInternalType('array', $gatheredFileData);
70
-        $this->assertEquals(count($files), count($gatheredFileData));
71
-        foreach ($gatheredFileData as $fileData) {
72
-            $this->assertInternalType('array', $fileData);
73
-            $this->assertArrayHasKey('name', $fileData);
74
-            $this->assertContains($fileData['name'], $files);
75
-            $this->assertArrayHasKey('size', $fileData);
76
-            $this->assertEquals($fileData['size'], filesize($fileData['name']));
77
-        }
78
-    }
79
-
80
-    public function testGatherMemoryData()
81
-    {
82
-        $memoryUsage = memory_get_peak_usage();
83
-        $allowedLimit = ini_get('memory_limit');
84
-        $profiler = new PhpQuickProfiler();
85
-        $gatheredMemoryData = $profiler->gatherMemoryData();
86
-
87
-        $this->assertInternalType('array', $gatheredMemoryData);
88
-        $this->assertEquals(2, count($gatheredMemoryData));
89
-        $this->assertArrayHasKey('used', $gatheredMemoryData);
90
-        $this->assertEquals($memoryUsage, $gatheredMemoryData['used']);
91
-        $this->assertArrayHasKey('allowed', $gatheredMemoryData);
92
-        $this->assertEquals($allowedLimit, $gatheredMemoryData['allowed']);
93
-    }
94
-
95
-    public function testSetProfiledQueries()
96
-    {
97
-        $profiledQueries = $this->dataProfiledQueries();
98
-        $profiler = new PhpQuickProfiler();
99
-        $profiler->setProfiledQueries($profiledQueries);
100
-
101
-        $this->assertAttributeEquals($profiledQueries, 'profiledQueries', $profiler);
102
-    }
103
-
104
-    public function testGatherQueryData()
105
-    {
106
-        $profiledQueries = $this->dataProfiledQueries();
107
-        $profiledQueriesSql = array();
108
-        $profiledQueriesTime = array();
109
-        foreach ($profiledQueries as $queryData) {
110
-            array_push($profiledQueriesSql, $queryData['sql']);
111
-            array_push($profiledQueriesTime, $queryData['time']);
112
-        }
113
-
114
-        $profiler = new PhpQuickProfiler();
115
-        $profiler->setProfiledQueries($profiledQueries);
116
-        $gatheredQueryData = $profiler->gatherQueryData(self::$dbConnection);
117
-
118
-        $this->assertInternalType('array', $gatheredQueryData);
119
-        $this->assertEquals(count($profiledQueries), count($gatheredQueryData));
120
-        foreach ($gatheredQueryData as $queryData) {
121
-            $this->assertInternalType('array', $queryData);
122
-            $this->assertArrayHasKey('sql', $queryData);
123
-            $this->assertContains($queryData['sql'], $profiledQueriesSql);
124
-            $this->assertArrayHasKey('explain', $queryData);
125
-            $this->assertInternaltype('array', $queryData['explain']);
126
-            $this->assertGreaterThan(0, count($queryData['explain']));
127
-            $this->assertArrayHasKey('time', $queryData);
128
-            $this->assertContains($queryData['time'], $profiledQueriesTime);
129
-        }
130
-    }
131
-
132
-    public function testGatherQueryDataInternalProfiler()
133
-    {
134
-        $profiledQueries = $this->dataProfiledQueries();
135
-        $dbConnection = self::$dbConnection;
136
-        $dbConnection->queries = $profiledQueries;
137
-        $profiler = new PhpQuickProfiler();
138
-        $profiler->gatherQueryData($dbConnection);
139
-
140
-        $this->assertAttributeSame($profiledQueries, 'profiledQueries', $profiler);
141
-    }
142
-
143
-    /**
144
-     * @dataProvider dataProfiledQueries
145
-     */
146
-    public function testExplainQuery($sql, $parameters)
147
-    {
148
-        $profiler = new PhpQuickProfiler();
149
-        $reflectedMethod = $this->getAccessibleMethod($profiler, 'explainQuery');
150
-
151
-        $explainedQuery = $reflectedMethod->invokeArgs(
152
-            $profiler,
153
-            array(self::$dbConnection, $sql, $parameters)
154
-        );
155
-        $this->assertInternalType('array', $explainedQuery);
156
-        $this->assertGreaterThan(0, count($explainedQuery));
157
-    }
158
-
159
-    /**
160
-     * @expectedException Exception
161
-     */
162
-    public function testExplainQueryBadQueryException()
163
-    {
164
-        $invalidQuery = 'SELECT * FROM `fake_table`';
165
-        $profiler = new PhpQuickProfiler();
166
-        $reflectedMethod = $this->getAccessibleMethod($profiler, 'explainQuery');
167
-
168
-        $reflectedMethod->invokeArgs(
169
-            $profiler,
170
-            array(self::$dbConnection, $invalidQuery)
171
-        );
172
-    }
173
-
174
-    /**
175
-     * @expectedException Exception
176
-     */
177
-    public function testExplainQueryBadParametersException()
178
-    {
179
-        $query = 'SELECT * FROM `testing` WHERE `title` = :title';
180
-        $invalidParams = array('id' => 1);
181
-        $profiler = new PhpQuickProfiler();
182
-        $reflectedMethod = $this->getAccessibleMethod($profiler, 'explainQuery');
183
-
184
-        $reflectedMethod->invokeArgs(
185
-            $profiler,
186
-            array(self::$dbConnection, $query, $invalidParams)
187
-        );
188
-    }
189
-
190
-    /**
191
-     * @dataProvider dataConnectionDrivers
192
-     */
193
-    public function testGetExplainQuery($driver, $prefix)
194
-    {
195
-        $query = 'SELECT * FROM `testing`';
196
-        $profiler = new PhpQuickProfiler();
197
-        $reflectedMethod = $this->getAccessibleMethod($profiler, 'getExplainQuery');
198
-
199
-        $explainQuery = $reflectedMethod->invokeArgs(
200
-            $profiler,
201
-            array($query, $driver)
202
-        );
203
-
204
-        $explainPrefix = str_replace($query, '', $explainQuery);
205
-        $explainPrefix = trim($explainPrefix);
206
-        $this->assertEquals($prefix, $explainPrefix);
207
-    }
208
-
209
-    /**
210
-     * @expectedException Exception
211
-     */
212
-    public function testGetExplainQueryUnsupportedDriver()
213
-    {
214
-        $query = 'SELECT * FROM `testing`';
215
-        $unsupportedDriver = 'zz';
216
-        $profiler = new PhpQuickProfiler();
217
-        $reflectedMethod = $this->getAccessibleMethod($profiler, 'getExplainQuery');
218
-
219
-        $reflectedMethod->invokeArgs(
220
-            $profiler,
221
-            array($query, $unsupportedDriver)
222
-        );
223
-    }
224
-
225
-    public function testGatherSpeedData()
226
-    {
227
-        $elapsedTime = 1.234;
228
-        $startTime = microtime(true) - $elapsedTime;
229
-        $allowedTime = ini_get('max_execution_time');
230
-        $profiler = new PhpQuickProfiler($startTime);
231
-        $gatheredSpeedData = $profiler->gatherSpeedData();
232
-
233
-        $this->assertInternalType('array', $gatheredSpeedData);
234
-        $this->assertEquals(2, count($gatheredSpeedData));
235
-        $this->assertArrayHasKey('elapsed', $gatheredSpeedData);
236
-        $this->assertEquals($elapsedTime, $gatheredSpeedData['elapsed']);
237
-        $this->assertArrayHasKey('allowed', $gatheredSpeedData);
238
-        $this->assertEquals($allowedTime, $gatheredSpeedData['allowed']);
239
-    }
240
-
241
-    public function testDisplay()
242
-    {
243
-        $console = new Console();
244
-        $profiler = new PhpQuickProfiler();
245
-
246
-        $reflectedProfiler = new ReflectionClass(get_class($profiler));
247
-        $reflectedProperty = $reflectedProfiler->getProperty('startTime');
248
-        $reflectedProperty->setAccessible(true);
249
-        $startTime = $reflectedProperty->getValue($profiler);
250
-
251
-        $expectedDisplay = new Display();
252
-        $expectedDisplay->setStartTime($startTime);
253
-        $expectedDisplay->setConsole($console);
254
-        $expectedDisplay->setFileData($profiler->gatherFileData());
255
-        $expectedDisplay->setMemoryData($profiler->gatherMemoryData());
256
-        $expectedDisplay->setQueryData($profiler->gatherQueryData());
257
-        $expectedDisplay->setSpeedData($profiler->gatherSpeedData());
258
-        ob_start();
259
-        $expectedDisplay->__invoke();
260
-        ob_end_clean();
261
-
262
-        $display = new Display();
263
-        $profiler->setConsole($console);
264
-        $profiler->setDisplay($display);
265
-        ob_start();
266
-        $profiler->display();
267
-        ob_end_clean();
268
-
269
-        $this->assertAttributeEquals($expectedDisplay, 'display', $profiler);
270
-    }
271
-
272
-    /**
273
-     * @expectedException Exception
274
-     */
275
-    public function testDisplayNothingSetException()
276
-    {
277
-        $profiler = new PhpQuickProfiler();
278
-        $profiler->display();
279
-    }
280
-
281
-    /**
282
-     * @expectedException Exception
283
-     */
284
-    public function testDisplayNoConsoleException()
285
-    {
286
-        $display = new Display();
287
-        $profiler = new PhpQuickProfiler();
288
-        $profiler->setDisplay($display);
289
-        $profiler->display();
290
-    }
291
-
292
-    /**
293
-     * @expectedException Exception
294
-     */
295
-    public function testDisplayNoDisplayException()
296
-    {
297
-        $console = new Console();
298
-        $profiler = new PhpQuickProfiler();
299
-        $profiler->setConsole($console);
300
-        $profiler->display();
301
-    }
302
-
303
-    public function dataProfiledQueries()
304
-    {
305
-        return array(
306
-            array(
307
-              'sql' => "SELECT * FROM testing",
308
-              'parameters' => array(),
309
-              'time' => 25
310
-            ),
311
-            array(
312
-              'sql' => "SELECT id FROM testing WHERE title = :title",
313
-              'parameters' => array('title' => 'beta'),
314
-              'time' => 5
315
-            )
316
-        );
317
-    }
318
-
319
-    public function dataConnectionDrivers()
320
-    {
321
-        return array(
322
-            array(
323
-                'driver' => 'mysql',
324
-                'prefix' => 'EXPLAIN'
325
-            ),
326
-            array(
327
-                'driver' => 'sqlite',
328
-                'prefix' => 'EXPLAIN QUERY PLAN'
329
-            )
330
-        );
331
-    }
332
-
333
-    protected function getAccessibleMethod(PhpQuickProfiler $profiler, $methodName)
334
-    {
335
-        $reflectedConsole = new ReflectionClass(get_class($profiler));
336
-        $reflectedMethod = $reflectedConsole->getMethod($methodName);
337
-        $reflectedMethod->setAccessible(true);
338
-        return $reflectedMethod;
339
-    }
340
-
341
-    public static function tearDownAfterClass()
342
-    {
343
-        self::$dbConnection = null;
344
-    }
31
+		self::$dbConnection->exec($hydrateTable);
32
+	}
33
+
34
+	public function testConstruct()
35
+	{
36
+		$startTime = microtime(true);
37
+
38
+		$profiler = new PhpQuickProfiler();
39
+		$this->assertAttributeEquals($startTime, 'startTime', $profiler);
40
+
41
+		$profiler = new PhpQuickProfiler($startTime);
42
+		$this->assertAttributeEquals($startTime, 'startTime', $profiler);
43
+	}
44
+
45
+	public function testSetConsole()
46
+	{
47
+		$console = new Console();
48
+		$profiler = new PhpQuickProfiler();
49
+		$profiler->setConsole($console);
50
+
51
+		$this->assertAttributeSame($console, 'console', $profiler);
52
+	}
53
+
54
+	public function testSetDisplay()
55
+	{
56
+		$display = new Display();
57
+		$profiler = new PhpQuickProfiler();
58
+		$profiler->setDisplay($display);
59
+
60
+		$this->assertAttributeSame($display, 'display', $profiler);
61
+	}
62
+
63
+	public function testGatherFileData()
64
+	{
65
+		$files = get_included_files();
66
+		$profiler = new PhpQuickProfiler();
67
+		$gatheredFileData = $profiler->gatherFileData();
68
+
69
+		$this->assertInternalType('array', $gatheredFileData);
70
+		$this->assertEquals(count($files), count($gatheredFileData));
71
+		foreach ($gatheredFileData as $fileData) {
72
+			$this->assertInternalType('array', $fileData);
73
+			$this->assertArrayHasKey('name', $fileData);
74
+			$this->assertContains($fileData['name'], $files);
75
+			$this->assertArrayHasKey('size', $fileData);
76
+			$this->assertEquals($fileData['size'], filesize($fileData['name']));
77
+		}
78
+	}
79
+
80
+	public function testGatherMemoryData()
81
+	{
82
+		$memoryUsage = memory_get_peak_usage();
83
+		$allowedLimit = ini_get('memory_limit');
84
+		$profiler = new PhpQuickProfiler();
85
+		$gatheredMemoryData = $profiler->gatherMemoryData();
86
+
87
+		$this->assertInternalType('array', $gatheredMemoryData);
88
+		$this->assertEquals(2, count($gatheredMemoryData));
89
+		$this->assertArrayHasKey('used', $gatheredMemoryData);
90
+		$this->assertEquals($memoryUsage, $gatheredMemoryData['used']);
91
+		$this->assertArrayHasKey('allowed', $gatheredMemoryData);
92
+		$this->assertEquals($allowedLimit, $gatheredMemoryData['allowed']);
93
+	}
94
+
95
+	public function testSetProfiledQueries()
96
+	{
97
+		$profiledQueries = $this->dataProfiledQueries();
98
+		$profiler = new PhpQuickProfiler();
99
+		$profiler->setProfiledQueries($profiledQueries);
100
+
101
+		$this->assertAttributeEquals($profiledQueries, 'profiledQueries', $profiler);
102
+	}
103
+
104
+	public function testGatherQueryData()
105
+	{
106
+		$profiledQueries = $this->dataProfiledQueries();
107
+		$profiledQueriesSql = array();
108
+		$profiledQueriesTime = array();
109
+		foreach ($profiledQueries as $queryData) {
110
+			array_push($profiledQueriesSql, $queryData['sql']);
111
+			array_push($profiledQueriesTime, $queryData['time']);
112
+		}
113
+
114
+		$profiler = new PhpQuickProfiler();
115
+		$profiler->setProfiledQueries($profiledQueries);
116
+		$gatheredQueryData = $profiler->gatherQueryData(self::$dbConnection);
117
+
118
+		$this->assertInternalType('array', $gatheredQueryData);
119
+		$this->assertEquals(count($profiledQueries), count($gatheredQueryData));
120
+		foreach ($gatheredQueryData as $queryData) {
121
+			$this->assertInternalType('array', $queryData);
122
+			$this->assertArrayHasKey('sql', $queryData);
123
+			$this->assertContains($queryData['sql'], $profiledQueriesSql);
124
+			$this->assertArrayHasKey('explain', $queryData);
125
+			$this->assertInternaltype('array', $queryData['explain']);
126
+			$this->assertGreaterThan(0, count($queryData['explain']));
127
+			$this->assertArrayHasKey('time', $queryData);
128
+			$this->assertContains($queryData['time'], $profiledQueriesTime);
129
+		}
130
+	}
131
+
132
+	public function testGatherQueryDataInternalProfiler()
133
+	{
134
+		$profiledQueries = $this->dataProfiledQueries();
135
+		$dbConnection = self::$dbConnection;
136
+		$dbConnection->queries = $profiledQueries;
137
+		$profiler = new PhpQuickProfiler();
138
+		$profiler->gatherQueryData($dbConnection);
139
+
140
+		$this->assertAttributeSame($profiledQueries, 'profiledQueries', $profiler);
141
+	}
142
+
143
+	/**
144
+	 * @dataProvider dataProfiledQueries
145
+	 */
146
+	public function testExplainQuery($sql, $parameters)
147
+	{
148
+		$profiler = new PhpQuickProfiler();
149
+		$reflectedMethod = $this->getAccessibleMethod($profiler, 'explainQuery');
150
+
151
+		$explainedQuery = $reflectedMethod->invokeArgs(
152
+			$profiler,
153
+			array(self::$dbConnection, $sql, $parameters)
154
+		);
155
+		$this->assertInternalType('array', $explainedQuery);
156
+		$this->assertGreaterThan(0, count($explainedQuery));
157
+	}
158
+
159
+	/**
160
+	 * @expectedException Exception
161
+	 */
162
+	public function testExplainQueryBadQueryException()
163
+	{
164
+		$invalidQuery = 'SELECT * FROM `fake_table`';
165
+		$profiler = new PhpQuickProfiler();
166
+		$reflectedMethod = $this->getAccessibleMethod($profiler, 'explainQuery');
167
+
168
+		$reflectedMethod->invokeArgs(
169
+			$profiler,
170
+			array(self::$dbConnection, $invalidQuery)
171
+		);
172
+	}
173
+
174
+	/**
175
+	 * @expectedException Exception
176
+	 */
177
+	public function testExplainQueryBadParametersException()
178
+	{
179
+		$query = 'SELECT * FROM `testing` WHERE `title` = :title';
180
+		$invalidParams = array('id' => 1);
181
+		$profiler = new PhpQuickProfiler();
182
+		$reflectedMethod = $this->getAccessibleMethod($profiler, 'explainQuery');
183
+
184
+		$reflectedMethod->invokeArgs(
185
+			$profiler,
186
+			array(self::$dbConnection, $query, $invalidParams)
187
+		);
188
+	}
189
+
190
+	/**
191
+	 * @dataProvider dataConnectionDrivers
192
+	 */
193
+	public function testGetExplainQuery($driver, $prefix)
194
+	{
195
+		$query = 'SELECT * FROM `testing`';
196
+		$profiler = new PhpQuickProfiler();
197
+		$reflectedMethod = $this->getAccessibleMethod($profiler, 'getExplainQuery');
198
+
199
+		$explainQuery = $reflectedMethod->invokeArgs(
200
+			$profiler,
201
+			array($query, $driver)
202
+		);
203
+
204
+		$explainPrefix = str_replace($query, '', $explainQuery);
205
+		$explainPrefix = trim($explainPrefix);
206
+		$this->assertEquals($prefix, $explainPrefix);
207
+	}
208
+
209
+	/**
210
+	 * @expectedException Exception
211
+	 */
212
+	public function testGetExplainQueryUnsupportedDriver()
213
+	{
214
+		$query = 'SELECT * FROM `testing`';
215
+		$unsupportedDriver = 'zz';
216
+		$profiler = new PhpQuickProfiler();
217
+		$reflectedMethod = $this->getAccessibleMethod($profiler, 'getExplainQuery');
218
+
219
+		$reflectedMethod->invokeArgs(
220
+			$profiler,
221
+			array($query, $unsupportedDriver)
222
+		);
223
+	}
224
+
225
+	public function testGatherSpeedData()
226
+	{
227
+		$elapsedTime = 1.234;
228
+		$startTime = microtime(true) - $elapsedTime;
229
+		$allowedTime = ini_get('max_execution_time');
230
+		$profiler = new PhpQuickProfiler($startTime);
231
+		$gatheredSpeedData = $profiler->gatherSpeedData();
232
+
233
+		$this->assertInternalType('array', $gatheredSpeedData);
234
+		$this->assertEquals(2, count($gatheredSpeedData));
235
+		$this->assertArrayHasKey('elapsed', $gatheredSpeedData);
236
+		$this->assertEquals($elapsedTime, $gatheredSpeedData['elapsed']);
237
+		$this->assertArrayHasKey('allowed', $gatheredSpeedData);
238
+		$this->assertEquals($allowedTime, $gatheredSpeedData['allowed']);
239
+	}
240
+
241
+	public function testDisplay()
242
+	{
243
+		$console = new Console();
244
+		$profiler = new PhpQuickProfiler();
245
+
246
+		$reflectedProfiler = new ReflectionClass(get_class($profiler));
247
+		$reflectedProperty = $reflectedProfiler->getProperty('startTime');
248
+		$reflectedProperty->setAccessible(true);
249
+		$startTime = $reflectedProperty->getValue($profiler);
250
+
251
+		$expectedDisplay = new Display();
252
+		$expectedDisplay->setStartTime($startTime);
253
+		$expectedDisplay->setConsole($console);
254
+		$expectedDisplay->setFileData($profiler->gatherFileData());
255
+		$expectedDisplay->setMemoryData($profiler->gatherMemoryData());
256
+		$expectedDisplay->setQueryData($profiler->gatherQueryData());
257
+		$expectedDisplay->setSpeedData($profiler->gatherSpeedData());
258
+		ob_start();
259
+		$expectedDisplay->__invoke();
260
+		ob_end_clean();
261
+
262
+		$display = new Display();
263
+		$profiler->setConsole($console);
264
+		$profiler->setDisplay($display);
265
+		ob_start();
266
+		$profiler->display();
267
+		ob_end_clean();
268
+
269
+		$this->assertAttributeEquals($expectedDisplay, 'display', $profiler);
270
+	}
271
+
272
+	/**
273
+	 * @expectedException Exception
274
+	 */
275
+	public function testDisplayNothingSetException()
276
+	{
277
+		$profiler = new PhpQuickProfiler();
278
+		$profiler->display();
279
+	}
280
+
281
+	/**
282
+	 * @expectedException Exception
283
+	 */
284
+	public function testDisplayNoConsoleException()
285
+	{
286
+		$display = new Display();
287
+		$profiler = new PhpQuickProfiler();
288
+		$profiler->setDisplay($display);
289
+		$profiler->display();
290
+	}
291
+
292
+	/**
293
+	 * @expectedException Exception
294
+	 */
295
+	public function testDisplayNoDisplayException()
296
+	{
297
+		$console = new Console();
298
+		$profiler = new PhpQuickProfiler();
299
+		$profiler->setConsole($console);
300
+		$profiler->display();
301
+	}
302
+
303
+	public function dataProfiledQueries()
304
+	{
305
+		return array(
306
+			array(
307
+			  'sql' => "SELECT * FROM testing",
308
+			  'parameters' => array(),
309
+			  'time' => 25
310
+			),
311
+			array(
312
+			  'sql' => "SELECT id FROM testing WHERE title = :title",
313
+			  'parameters' => array('title' => 'beta'),
314
+			  'time' => 5
315
+			)
316
+		);
317
+	}
318
+
319
+	public function dataConnectionDrivers()
320
+	{
321
+		return array(
322
+			array(
323
+				'driver' => 'mysql',
324
+				'prefix' => 'EXPLAIN'
325
+			),
326
+			array(
327
+				'driver' => 'sqlite',
328
+				'prefix' => 'EXPLAIN QUERY PLAN'
329
+			)
330
+		);
331
+	}
332
+
333
+	protected function getAccessibleMethod(PhpQuickProfiler $profiler, $methodName)
334
+	{
335
+		$reflectedConsole = new ReflectionClass(get_class($profiler));
336
+		$reflectedMethod = $reflectedConsole->getMethod($methodName);
337
+		$reflectedMethod->setAccessible(true);
338
+		return $reflectedMethod;
339
+	}
340
+
341
+	public static function tearDownAfterClass()
342
+	{
343
+		self::$dbConnection = null;
344
+	}
345 345
 }
Please login to merge, or discard this patch.
tests/helpers/function-overrides.php 1 patch
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -5,43 +5,43 @@
 block discarded – undo
5 5
 // namespace hack on microtime functionality
6 6
 function microtime()
7 7
 {
8
-    return 1450355136.5706;
8
+	return 1450355136.5706;
9 9
 }
10 10
 
11 11
 // namespace hack on included files functionality
12 12
 function get_included_files()
13 13
 {
14
-    return array(
15
-        'index.php',
16
-        'src/Class.php'
17
-    );
14
+	return array(
15
+		'index.php',
16
+		'src/Class.php'
17
+	);
18 18
 }
19 19
 
20 20
 // namespace hack on filesize
21 21
 function filesize($filename)
22 22
 {
23
-    return strlen($filename) * 100;
23
+	return strlen($filename) * 100;
24 24
 }
25 25
 
26 26
 // namespace hack on memory usage
27 27
 function memory_get_usage()
28 28
 {
29
-    return 12345678;
29
+	return 12345678;
30 30
 }
31 31
 
32 32
 // namespace hack on memory usage
33 33
 function memory_get_peak_usage()
34 34
 {
35
-    return 123456789;
35
+	return 123456789;
36 36
 }
37 37
 
38 38
 // namespace hack on ini settings
39 39
 function ini_get($setting)
40 40
 {
41
-    if ($setting == 'memory_limit') {
42
-        return '128M';
43
-    } elseif ($setting == 'max_execution_time') {
44
-        return '30';
45
-    }
46
-    return \ini_get($setting);
41
+	if ($setting == 'memory_limit') {
42
+		return '128M';
43
+	} elseif ($setting == 'max_execution_time') {
44
+		return '30';
45
+	}
46
+	return \ini_get($setting);
47 47
 }
Please login to merge, or discard this patch.
tests/unit/DisplayTest.php 3 patches
Doc Comments   +8 added lines patch added patch discarded remove patch
@@ -228,6 +228,10 @@  discard block
 block discarded – undo
228 228
         );
229 229
     }
230 230
 
231
+    /**
232
+     * @param Console $class
233
+     * @param string $property
234
+     */
231 235
     protected function setInternalProperty($class, $property, $value)
232 236
     {
233 237
         $reflectedClass = new ReflectionClass(get_class($class));
@@ -236,6 +240,10 @@  discard block
 block discarded – undo
236 240
         $reflectedProperty->setValue($class, $value);
237 241
     }
238 242
 
243
+    /**
244
+     * @param Display $class
245
+     * @param string $method
246
+     */
239 247
     protected function getAccessibleMethod($class, $method)
240 248
     {
241 249
         $reflectedClass = new ReflectionClass(get_class($class));
Please login to merge, or discard this patch.
Indentation   +512 added lines, -512 removed lines patch added patch discarded remove patch
@@ -9,516 +9,516 @@
 block discarded – undo
9 9
 class DisplayTest extends PHPUnit_Framework_TestCase
10 10
 {
11 11
 
12
-    public function testConstruct()
13
-    {
14
-        $display = new Display();
15
-        $reflectedDisplay = new ReflectionClass(get_class($display));
16
-        $reflectedProperty = $reflectedDisplay->getProperty('defaults');
17
-        $reflectedProperty->setAccessible(true);
18
-        $defaults = $reflectedProperty->getValue($display);
19
-
20
-        $display = new Display();
21
-        $this->assertAttributeEquals($defaults, 'options', $display);
22
-        $this->assertAttributeGreaterThan(0, 'pathTrimStart', $display);
23
-
24
-        $options = array(
25
-            'script_path' => 'testing/testing.js',
26
-            'fake_key' => 'foo bar',
27
-            'relative_path' => false,
28
-        );
29
-        $expectedOptions = array_intersect_key($options, $defaults);
30
-        $expectedOptions = array_replace($defaults, $expectedOptions);
31
-        $display = new Display($options);
32
-        $this->assertAttributeEquals($expectedOptions, 'options', $display);
33
-        $this->assertAttributeEquals(0, 'pathTrimStart', $display);
34
-    }
35
-
36
-    public function testSetStartTime()
37
-    {
38
-        $startTime = microtime(true);
39
-        $display = new Display();
40
-        $display->setStartTime($startTime);
41
-
42
-        $this->assertAttributeEquals($startTime, 'startTime', $display);
43
-    }
44
-
45
-    public function testSetConsole()
46
-    {
47
-        $console = new Console();
48
-        $display = new Display();
49
-        $display->setConsole($console);
50
-
51
-        $this->assertAttributeSame($console, 'console', $display);
52
-    }
53
-
54
-    public function testSetMemoryData()
55
-    {
56
-        $memoryData = array(
57
-            'used'    => memory_get_peak_usage(),
58
-            'allowed' => ini_get('memory_limit')
59
-        );
60
-        $display = new Display();
61
-        $display->setMemoryData($memoryData);
62
-
63
-        $this->assertAttributeEquals($memoryData, 'memoryData', $display);
64
-    }
65
-
66
-    public function testSetQueryData()
67
-    {
68
-        $queryData = array(
69
-            'sql'     => 'SELECT * FROM testing',
70
-            'explain' => array(
71
-                'key' => 'value'
72
-            ),
73
-            'time'    => 300
74
-        );
75
-        $display = new Display();
76
-        $display->setQueryData($queryData);
77
-
78
-        $this->assertAttributeEquals($queryData, 'queryData', $display);
79
-    }
80
-
81
-    public function testSetSpeedData()
82
-    {
83
-        $speedData = array(
84
-            'elapsed' => 1.234,
85
-            'allowed' => 30
86
-        );
87
-        $display = new Display();
88
-        $display->setSpeedData($speedData);
89
-
90
-        $this->assertAttributeEquals($speedData, 'speedData', $display);
91
-    }
92
-
93
-    /**
94
-     * @dataProvider dataPathTrimStart
95
-     */
96
-    public function testGetPathTrimStart($cwd, $dir, $expectedPosition)
97
-    {
98
-        $display = new Display();
99
-        $reflectedMethod = $this->getAccessibleMethod($display, 'getPathTrimStart');
100
-        $position = $reflectedMethod->invokeArgs($display, array($cwd, $dir));
101
-
102
-        $this->assertEquals($expectedPosition, $position);
103
-    }
104
-
105
-    /**
106
-     * @dataProvider dataConsoleStore
107
-     */
108
-    public function testGetConsoleMeta($consoleStore, $expectedMeta, $expectedMessages)
109
-    {
110
-        $console = new Console();
111
-        $this->setInternalProperty($console, 'store', $consoleStore);
112
-        $display = new Display();
113
-        $display->setConsole($console);
114
-        $reflectedMethod = $this->getAccessibleMethod($display, 'getConsoleMeta');
115
-
116
-        $consoleMeta = $reflectedMethod->invoke($display);
117
-        $this->assertEquals($expectedMeta, $consoleMeta);
118
-    }
119
-
120
-    /**
121
-     * @dataProvider dataConsoleStore
122
-     */
123
-    public function testGetConsoleMessages($consoleStore, $expectedMeta, $expectedMessages)
124
-    {
125
-        $console = new Console();
126
-        $this->setInternalProperty($console, 'store', $consoleStore);
127
-        $display = new Display();
128
-        $display->setConsole($console);
129
-        $reflectedMethod = $this->getAccessibleMethod($display, 'getConsoleMessages');
130
-
131
-        $consoleMessages = $reflectedMethod->invoke($display);
132
-        $this->assertEquals($expectedMessages, $consoleMessages);
133
-    }
134
-
135
-    public function testGetSpeedMeta()
136
-    {
137
-        $elapsedTime = 1234.678;
138
-        $allowedTime = 30;
139
-        $display = new Display();
140
-        $display->setSpeedData(array(
141
-            'elapsed' => $elapsedTime,
142
-            'allowed' => $allowedTime
143
-        ));
144
-        $reflectedMethod = $this->getAccessibleMethod($display, 'getReadableTime');
145
-        $elapsedTime = $reflectedMethod->invokeArgs($display, array($elapsedTime));
146
-        $allowedTime = $reflectedMethod->invokeArgs($display, array($allowedTime, 0));
147
-        $expectedMeta = array(
148
-            'elapsed' => $elapsedTime,
149
-            'allowed' => $allowedTime
150
-        );
151
-
152
-        $reflectedMethod = $this->getAccessibleMethod($display, 'getSpeedMeta');
153
-        $speedMeta = $reflectedMethod->invoke($display);
154
-        $this->assertEquals($expectedMeta, $speedMeta);
155
-    }
156
-
157
-    /**
158
-     * @dataProvider dataQueryData
159
-     */
160
-    public function testGetQueryMeta($queryData, $expectedMeta, $expectedList)
161
-    {
162
-        $display = new Display();
163
-        $display->setQueryData($queryData);
164
-        $reflectedMethod = $this->getAccessibleMethod($display, 'getQueryMeta');
165
-
166
-        $queryMeta = $reflectedMethod->invoke($display);
167
-        $this->assertEquals($expectedMeta, $queryMeta);
168
-    }
169
-
170
-    /**
171
-     * @dataProvider dataQueryData
172
-     */
173
-    public function testGetQueryList($queryData, $expectedMeta, $expectedList)
174
-    {
175
-        $display = new Display();
176
-        $display->setQueryData($queryData);
177
-        $reflectedMethod = $this->getAccessibleMethod($display, 'getQueryList');
178
-
179
-        $queryList = $reflectedMethod->invoke($display);
180
-        $this->assertEquals($expectedList, $queryList);
181
-    }
182
-
183
-    public function testGetMemoryMeta()
184
-    {
185
-        $usedMemory = 123456;
186
-        $allowedMemory = '128M';
187
-        $display = new Display();
188
-        $display->setMemoryData(array(
189
-            'used'    => $usedMemory,
190
-            'allowed' => $allowedMemory
191
-        ));
192
-        $reflectedMethod = $this->getAccessibleMethod($display, 'getReadableMemory');
193
-        $usedMemory = $reflectedMethod->invokeArgs($display, array($usedMemory));
194
-        $expectedMeta = array(
195
-            'used'    => $usedMemory,
196
-            'allowed' => $allowedMemory
197
-        );
198
-
199
-        $reflectedMethod = $this->getAccessibleMethod($display, 'getMemoryMeta');
200
-        $memoryMeta = $reflectedMethod->invoke($display);
201
-        $this->assertEquals($expectedMeta, $memoryMeta);
202
-    }
203
-
204
-    /**
205
-     * @dataProvider dataFileData
206
-     */
207
-    public function testGetFileMeta($fileData, $expectedMeta, $expectedList)
208
-    {
209
-        $display = new Display();
210
-        $display->setFileData($fileData);
211
-        $reflectedMethod = $this->getAccessibleMethod($display, 'getFileMeta');
212
-
213
-        $fileMeta = $reflectedMethod->invoke($display);
214
-        $this->assertEquals($expectedMeta, $fileMeta);
215
-    }
216
-
217
-    /**
218
-     * @dataProvider dataFileData
219
-     */
220
-    public function testGetFileList($fileData, $expectedMeta, $expectedList)
221
-    {
222
-        $display = new Display();
223
-        $display->setFileData($fileData);
224
-        $reflectedMethod = $this->getAccessibleMethod($display, 'getFileList');
225
-
226
-        $fileList = $reflectedMethod->invoke($display);
227
-        $this->assertEquals($expectedList, $fileList);
228
-    }
229
-
230
-    public function testFilterMessages()
231
-    {
232
-        $display = new Display();
233
-        $reflectedMethod = $this->getAccessibleMethod($display, 'filterMessages');
234
-
235
-        $filteredMessages = $reflectedMethod->invokeArgs($display, array(array(array(
236
-            'type' => 'remove'
237
-        )), 'keep'));
238
-        $this->assertEmpty($filteredMessages);
239
-        $filteredMessages = $reflectedMethod->invokeArgs($display, array(array(array(
240
-            'type' => 'keep'
241
-        )), 'keep'));
242
-        $this->assertCount(1, $filteredMessages);
243
-    }
244
-
245
-    public function testGetReadableTime()
246
-    {
247
-        $timeTest = array(
248
-            '.032432' => '32 ms',
249
-            '24.3781' => '24.378 s',
250
-            '145.123' => '2.419 m'
251
-        );
252
-        $display = new Display();
253
-        $reflectedMethod = $this->getAccessibleMethod($display, 'getReadableTime');
254
-
255
-        foreach ($timeTest as $rawTime => $expectedTime) {
256
-            $readableTime = $reflectedMethod->invokeArgs($display, array($rawTime));
257
-            $this->assertEquals($expectedTime, $readableTime);
258
-        }
259
-    }
260
-
261
-    public function testGetReadableMemory()
262
-    {
263
-        $memoryTest = array(
264
-            '314'     => '314 b',
265
-            '7403'    => '7.23 k',
266
-            '2589983' => '2.47 M'
267
-        );
268
-        $display = new Display();
269
-        $reflectedMethod = $this->getAccessibleMethod($display, 'getReadableMemory');
270
-
271
-        foreach ($memoryTest as $rawMemory => $expectedMemory) {
272
-            $readableMemory = $reflectedMethod->invokeArgs($display, array($rawMemory));
273
-            $this->assertEquals($expectedMemory, $readableMemory);
274
-        }
275
-    }
276
-
277
-    public function testGetFilePath()
278
-    {
279
-        $display = new Display(array('relative_path' => false));
280
-        $path = getcwd() . '/puppies';
281
-        $reflectedFilePath = $this->getAccessibleMethod($display, 'getFilePath');
282
-        $path = $reflectedFilePath->invokeArgs($display, array($path));
283
-        $expectedPath = getcwd() . '/puppies';
284
-
285
-        $this->assertEquals($expectedPath, $path);
286
-
287
-        $display = new Display();
288
-        $path = getcwd() . '/puppies';
289
-        $reflectedFilePath = $this->getAccessibleMethod($display, 'getFilePath');
290
-        $path = $reflectedFilePath->invokeArgs($display, array($path));
291
-        $expectedPath = '/puppies';
292
-
293
-        $this->assertEquals($expectedPath, $path);
294
-    }
295
-
296
-    public function dataConsoleStore()
297
-    {
298
-        $testException = new Exception('testing');
299
-        $display = new Display();
300
-        $reflectedPathTrim = $this->getAccessibleMethod($display, 'getPathTrimStart');
301
-        $trimStart = $reflectedPathTrim->invokeArgs($display, array(getcwd(), __DIR__));
302
-        $reflectedTime = $this->getAccessibleMethod($display, 'getReadableTime');
303
-        $reflectedMemory = $this->getAccessibleMethod($display, 'getReadableMemory');
304
-
305
-        return array(
306
-            array(
307
-                'store' => array(
308
-                    array(
309
-                        'data' => 'testing message',
310
-                        'type' => 'log'
311
-                    ),
312
-                    array(
313
-                        'name' => 'now',
314
-                        'data' => microtime(true),
315
-                        'type' => 'speed'
316
-                    ),
317
-                    array(
318
-                        'name' => 'little later',
319
-                        'data' => microtime(true) + 1,
320
-                        'type' => 'speed'
321
-                    ),
322
-                    array(
323
-                        'name' => 'invalid key',
324
-                        'type' => 'foo'
325
-                    )
326
-                ),
327
-                'meta' => array(
328
-                    'log'    => 1,
329
-                    'memory' => 0,
330
-                    'error'  => 1,
331
-                    'speed'  => 2
332
-                ),
333
-                'messages' => array(
334
-                    array(
335
-                        'message' => 'testing message',
336
-                        'type'    => 'log'
337
-                    ),
338
-                    array(
339
-                        'message' => 'now',
340
-                        'data'    => $reflectedTime->invokeArgs($display, array(microtime(true))),
341
-                        'type'    => 'speed'
342
-                    ),
343
-                    array(
344
-                        'message' => 'little later',
345
-                        'data'    => $reflectedTime->invokeArgs($display, array(microtime(true) + 1)),
346
-                        'type'    => 'speed'
347
-                    ),
348
-                    array(
349
-                        'message' => 'Unrecognized console log type: foo',
350
-                        'type'    => 'error'
351
-                    )
352
-                )
353
-            ),
354
-            array(
355
-                'store' => array(
356
-                    array(
357
-                        'data' => 'another testing message',
358
-                        'type' => 'log'
359
-                    ),
360
-                    array(
361
-                        'name'      => 'test array',
362
-                        'data'      => strlen(serialize(array('key' => 'value'))),
363
-                        'data_type' => 'array',
364
-                        'type'      => 'memory'
365
-                    ),
366
-                    array(
367
-                        'name'      => 'memory usage test',
368
-                        'data'      => memory_get_usage(),
369
-                        'data_type' => '',
370
-                        'type'      => 'memory'
371
-                    ),
372
-                    array(
373
-                        'data' => $testException->getMessage(),
374
-                        'file' => $testException->getFile(),
375
-                        'line' => $testException->getLine(),
376
-                        'type' => 'error'
377
-                    )
378
-                ),
379
-                'meta' => array(
380
-                    'log'    => 1,
381
-                    'memory' => 2,
382
-                    'error'  => 1,
383
-                    'speed'  => 0
384
-                ),
385
-                'messages' => array(
386
-                    array(
387
-                        'message' => 'another testing message',
388
-                        'type'    => 'log'
389
-                    ),
390
-                    array(
391
-                        'message' => 'array: test array',
392
-                        'data'    => $reflectedMemory->invokeArgs(
393
-                            $display,
394
-                            array(strlen(serialize(array('key' => 'value'))))
395
-                        ),
396
-                        'type'    => 'memory'
397
-                    ),
398
-                    array(
399
-                        'message' => 'memory usage test',
400
-                        'data'    => $reflectedMemory->invokeArgs($display, array(memory_get_usage())),
401
-                        'type'    => 'memory'
402
-                    ),
403
-                    array(
404
-                        'message' => sprintf(
405
-                            'Line %s: %s in %s',
406
-                            $testException->getLine(),
407
-                            $testException->getMessage(),
408
-                            substr($testException->getFile(), $trimStart)
409
-                        ),
410
-                        'type'    => 'error'
411
-                    )
412
-                )
413
-            )
414
-        );
415
-    }
416
-
417
-    public function dataPathTrimStart()
418
-    {
419
-        return array(
420
-            array(
421
-                'cwd' => '/Users/fakeUser/project',
422
-                'dir' => '/Users/fakeUser/project/vendor/particletree/pqp/tests/unit',
423
-                'expectedPosition' => 23,
424
-            ),
425
-            array(
426
-                'cwd' => '/Users/fakeUser/project/public/path',
427
-                'dir' => '/Users/fakeUser/project/vendor/particletree/pqp/tests/unit',
428
-                'expectedPosition' => 24,
429
-            ),
430
-        );
431
-    }
432
-
433
-    public function dataQueryData()
434
-    {
435
-        $display = new Display();
436
-        $reflectedTime = $this->getAccessibleMethod($display, 'getReadableTime');
437
-
438
-        return array(
439
-            array(
440
-                'data' => array(
441
-                    array(
442
-                        'sql'     => "SELECT * FROM testing",
443
-                        'explain' => array('empty_key' => ''),
444
-                        'time'    => 25
445
-                    ),
446
-                    array(
447
-                        'sql'     => "SELECT id FROM testing WHERE title = :title",
448
-                        'explain' => array('key' => 'value'),
449
-                        'time'    => 5
450
-                    )
451
-                ),
452
-                'meta' => array(
453
-                    'count'   => 2,
454
-                    'time'    => $reflectedTime->invokeArgs($display, array(30)),
455
-                    'slowest' => $reflectedTime->invokeArgs($display, array(25)),
456
-                ),
457
-                'list' => array(
458
-                    array(
459
-                        'message'  => 'SELECT * FROM testing',
460
-                        'sub_data' => array(),
461
-                        'data'     => $reflectedTime->invokeArgs($display, array(25))
462
-                    ),
463
-                    array(
464
-                        'message'  => 'SELECT id FROM testing WHERE title = :title',
465
-                        'sub_data' => array('key' => 'value'),
466
-                        'data'     => $reflectedTime->invokeArgs($display, array(5))
467
-                    )
468
-                )
469
-            )
470
-        );
471
-    }
472
-
473
-    public function dataFileData()
474
-    {
475
-        $display = new Display();
476
-        $reflectedMemory = $this->getAccessibleMethod($display, 'getReadableMemory');
477
-
478
-        return array(
479
-            array(
480
-                'data' => array(
481
-                    array(
482
-                        'name' => getcwd() . '/test-file',
483
-                        'size' => 1234
484
-                    ),
485
-                    array(
486
-                        'name' => getcwd() . '/test-file-2',
487
-                        'size' => 66
488
-                    )
489
-                ),
490
-                'meta' => array(
491
-                    'count'   => 2,
492
-                    'size'    => $reflectedMemory->invokeArgs($display, array(1300)),
493
-                    'largest' => $reflectedMemory->invokeArgs($display, array(1234)),
494
-                ),
495
-                'list' => array(
496
-                    array(
497
-                        'message' => '/test-file',
498
-                        'data'    => $reflectedMemory->invokeArgs($display, array(1234))
499
-                    ),
500
-                    array(
501
-                        'message' => '/test-file-2',
502
-                        'data'    => $reflectedMemory->invokeArgs($display, array(66))
503
-                    )
504
-                )
505
-            )
506
-        );
507
-    }
508
-
509
-    protected function setInternalProperty($class, $property, $value)
510
-    {
511
-        $reflectedClass = new ReflectionClass(get_class($class));
512
-        $reflectedProperty = $reflectedClass->getProperty($property);
513
-        $reflectedProperty->setAccessible(true);
514
-        $reflectedProperty->setValue($class, $value);
515
-    }
516
-
517
-    protected function getAccessibleMethod($class, $method)
518
-    {
519
-        $reflectedClass = new ReflectionClass(get_class($class));
520
-        $reflectedMethod = $reflectedClass->getMethod($method);
521
-        $reflectedMethod->setAccessible(true);
522
-        return $reflectedMethod;
523
-    }
12
+	public function testConstruct()
13
+	{
14
+		$display = new Display();
15
+		$reflectedDisplay = new ReflectionClass(get_class($display));
16
+		$reflectedProperty = $reflectedDisplay->getProperty('defaults');
17
+		$reflectedProperty->setAccessible(true);
18
+		$defaults = $reflectedProperty->getValue($display);
19
+
20
+		$display = new Display();
21
+		$this->assertAttributeEquals($defaults, 'options', $display);
22
+		$this->assertAttributeGreaterThan(0, 'pathTrimStart', $display);
23
+
24
+		$options = array(
25
+			'script_path' => 'testing/testing.js',
26
+			'fake_key' => 'foo bar',
27
+			'relative_path' => false,
28
+		);
29
+		$expectedOptions = array_intersect_key($options, $defaults);
30
+		$expectedOptions = array_replace($defaults, $expectedOptions);
31
+		$display = new Display($options);
32
+		$this->assertAttributeEquals($expectedOptions, 'options', $display);
33
+		$this->assertAttributeEquals(0, 'pathTrimStart', $display);
34
+	}
35
+
36
+	public function testSetStartTime()
37
+	{
38
+		$startTime = microtime(true);
39
+		$display = new Display();
40
+		$display->setStartTime($startTime);
41
+
42
+		$this->assertAttributeEquals($startTime, 'startTime', $display);
43
+	}
44
+
45
+	public function testSetConsole()
46
+	{
47
+		$console = new Console();
48
+		$display = new Display();
49
+		$display->setConsole($console);
50
+
51
+		$this->assertAttributeSame($console, 'console', $display);
52
+	}
53
+
54
+	public function testSetMemoryData()
55
+	{
56
+		$memoryData = array(
57
+			'used'    => memory_get_peak_usage(),
58
+			'allowed' => ini_get('memory_limit')
59
+		);
60
+		$display = new Display();
61
+		$display->setMemoryData($memoryData);
62
+
63
+		$this->assertAttributeEquals($memoryData, 'memoryData', $display);
64
+	}
65
+
66
+	public function testSetQueryData()
67
+	{
68
+		$queryData = array(
69
+			'sql'     => 'SELECT * FROM testing',
70
+			'explain' => array(
71
+				'key' => 'value'
72
+			),
73
+			'time'    => 300
74
+		);
75
+		$display = new Display();
76
+		$display->setQueryData($queryData);
77
+
78
+		$this->assertAttributeEquals($queryData, 'queryData', $display);
79
+	}
80
+
81
+	public function testSetSpeedData()
82
+	{
83
+		$speedData = array(
84
+			'elapsed' => 1.234,
85
+			'allowed' => 30
86
+		);
87
+		$display = new Display();
88
+		$display->setSpeedData($speedData);
89
+
90
+		$this->assertAttributeEquals($speedData, 'speedData', $display);
91
+	}
92
+
93
+	/**
94
+	 * @dataProvider dataPathTrimStart
95
+	 */
96
+	public function testGetPathTrimStart($cwd, $dir, $expectedPosition)
97
+	{
98
+		$display = new Display();
99
+		$reflectedMethod = $this->getAccessibleMethod($display, 'getPathTrimStart');
100
+		$position = $reflectedMethod->invokeArgs($display, array($cwd, $dir));
101
+
102
+		$this->assertEquals($expectedPosition, $position);
103
+	}
104
+
105
+	/**
106
+	 * @dataProvider dataConsoleStore
107
+	 */
108
+	public function testGetConsoleMeta($consoleStore, $expectedMeta, $expectedMessages)
109
+	{
110
+		$console = new Console();
111
+		$this->setInternalProperty($console, 'store', $consoleStore);
112
+		$display = new Display();
113
+		$display->setConsole($console);
114
+		$reflectedMethod = $this->getAccessibleMethod($display, 'getConsoleMeta');
115
+
116
+		$consoleMeta = $reflectedMethod->invoke($display);
117
+		$this->assertEquals($expectedMeta, $consoleMeta);
118
+	}
119
+
120
+	/**
121
+	 * @dataProvider dataConsoleStore
122
+	 */
123
+	public function testGetConsoleMessages($consoleStore, $expectedMeta, $expectedMessages)
124
+	{
125
+		$console = new Console();
126
+		$this->setInternalProperty($console, 'store', $consoleStore);
127
+		$display = new Display();
128
+		$display->setConsole($console);
129
+		$reflectedMethod = $this->getAccessibleMethod($display, 'getConsoleMessages');
130
+
131
+		$consoleMessages = $reflectedMethod->invoke($display);
132
+		$this->assertEquals($expectedMessages, $consoleMessages);
133
+	}
134
+
135
+	public function testGetSpeedMeta()
136
+	{
137
+		$elapsedTime = 1234.678;
138
+		$allowedTime = 30;
139
+		$display = new Display();
140
+		$display->setSpeedData(array(
141
+			'elapsed' => $elapsedTime,
142
+			'allowed' => $allowedTime
143
+		));
144
+		$reflectedMethod = $this->getAccessibleMethod($display, 'getReadableTime');
145
+		$elapsedTime = $reflectedMethod->invokeArgs($display, array($elapsedTime));
146
+		$allowedTime = $reflectedMethod->invokeArgs($display, array($allowedTime, 0));
147
+		$expectedMeta = array(
148
+			'elapsed' => $elapsedTime,
149
+			'allowed' => $allowedTime
150
+		);
151
+
152
+		$reflectedMethod = $this->getAccessibleMethod($display, 'getSpeedMeta');
153
+		$speedMeta = $reflectedMethod->invoke($display);
154
+		$this->assertEquals($expectedMeta, $speedMeta);
155
+	}
156
+
157
+	/**
158
+	 * @dataProvider dataQueryData
159
+	 */
160
+	public function testGetQueryMeta($queryData, $expectedMeta, $expectedList)
161
+	{
162
+		$display = new Display();
163
+		$display->setQueryData($queryData);
164
+		$reflectedMethod = $this->getAccessibleMethod($display, 'getQueryMeta');
165
+
166
+		$queryMeta = $reflectedMethod->invoke($display);
167
+		$this->assertEquals($expectedMeta, $queryMeta);
168
+	}
169
+
170
+	/**
171
+	 * @dataProvider dataQueryData
172
+	 */
173
+	public function testGetQueryList($queryData, $expectedMeta, $expectedList)
174
+	{
175
+		$display = new Display();
176
+		$display->setQueryData($queryData);
177
+		$reflectedMethod = $this->getAccessibleMethod($display, 'getQueryList');
178
+
179
+		$queryList = $reflectedMethod->invoke($display);
180
+		$this->assertEquals($expectedList, $queryList);
181
+	}
182
+
183
+	public function testGetMemoryMeta()
184
+	{
185
+		$usedMemory = 123456;
186
+		$allowedMemory = '128M';
187
+		$display = new Display();
188
+		$display->setMemoryData(array(
189
+			'used'    => $usedMemory,
190
+			'allowed' => $allowedMemory
191
+		));
192
+		$reflectedMethod = $this->getAccessibleMethod($display, 'getReadableMemory');
193
+		$usedMemory = $reflectedMethod->invokeArgs($display, array($usedMemory));
194
+		$expectedMeta = array(
195
+			'used'    => $usedMemory,
196
+			'allowed' => $allowedMemory
197
+		);
198
+
199
+		$reflectedMethod = $this->getAccessibleMethod($display, 'getMemoryMeta');
200
+		$memoryMeta = $reflectedMethod->invoke($display);
201
+		$this->assertEquals($expectedMeta, $memoryMeta);
202
+	}
203
+
204
+	/**
205
+	 * @dataProvider dataFileData
206
+	 */
207
+	public function testGetFileMeta($fileData, $expectedMeta, $expectedList)
208
+	{
209
+		$display = new Display();
210
+		$display->setFileData($fileData);
211
+		$reflectedMethod = $this->getAccessibleMethod($display, 'getFileMeta');
212
+
213
+		$fileMeta = $reflectedMethod->invoke($display);
214
+		$this->assertEquals($expectedMeta, $fileMeta);
215
+	}
216
+
217
+	/**
218
+	 * @dataProvider dataFileData
219
+	 */
220
+	public function testGetFileList($fileData, $expectedMeta, $expectedList)
221
+	{
222
+		$display = new Display();
223
+		$display->setFileData($fileData);
224
+		$reflectedMethod = $this->getAccessibleMethod($display, 'getFileList');
225
+
226
+		$fileList = $reflectedMethod->invoke($display);
227
+		$this->assertEquals($expectedList, $fileList);
228
+	}
229
+
230
+	public function testFilterMessages()
231
+	{
232
+		$display = new Display();
233
+		$reflectedMethod = $this->getAccessibleMethod($display, 'filterMessages');
234
+
235
+		$filteredMessages = $reflectedMethod->invokeArgs($display, array(array(array(
236
+			'type' => 'remove'
237
+		)), 'keep'));
238
+		$this->assertEmpty($filteredMessages);
239
+		$filteredMessages = $reflectedMethod->invokeArgs($display, array(array(array(
240
+			'type' => 'keep'
241
+		)), 'keep'));
242
+		$this->assertCount(1, $filteredMessages);
243
+	}
244
+
245
+	public function testGetReadableTime()
246
+	{
247
+		$timeTest = array(
248
+			'.032432' => '32 ms',
249
+			'24.3781' => '24.378 s',
250
+			'145.123' => '2.419 m'
251
+		);
252
+		$display = new Display();
253
+		$reflectedMethod = $this->getAccessibleMethod($display, 'getReadableTime');
254
+
255
+		foreach ($timeTest as $rawTime => $expectedTime) {
256
+			$readableTime = $reflectedMethod->invokeArgs($display, array($rawTime));
257
+			$this->assertEquals($expectedTime, $readableTime);
258
+		}
259
+	}
260
+
261
+	public function testGetReadableMemory()
262
+	{
263
+		$memoryTest = array(
264
+			'314'     => '314 b',
265
+			'7403'    => '7.23 k',
266
+			'2589983' => '2.47 M'
267
+		);
268
+		$display = new Display();
269
+		$reflectedMethod = $this->getAccessibleMethod($display, 'getReadableMemory');
270
+
271
+		foreach ($memoryTest as $rawMemory => $expectedMemory) {
272
+			$readableMemory = $reflectedMethod->invokeArgs($display, array($rawMemory));
273
+			$this->assertEquals($expectedMemory, $readableMemory);
274
+		}
275
+	}
276
+
277
+	public function testGetFilePath()
278
+	{
279
+		$display = new Display(array('relative_path' => false));
280
+		$path = getcwd() . '/puppies';
281
+		$reflectedFilePath = $this->getAccessibleMethod($display, 'getFilePath');
282
+		$path = $reflectedFilePath->invokeArgs($display, array($path));
283
+		$expectedPath = getcwd() . '/puppies';
284
+
285
+		$this->assertEquals($expectedPath, $path);
286
+
287
+		$display = new Display();
288
+		$path = getcwd() . '/puppies';
289
+		$reflectedFilePath = $this->getAccessibleMethod($display, 'getFilePath');
290
+		$path = $reflectedFilePath->invokeArgs($display, array($path));
291
+		$expectedPath = '/puppies';
292
+
293
+		$this->assertEquals($expectedPath, $path);
294
+	}
295
+
296
+	public function dataConsoleStore()
297
+	{
298
+		$testException = new Exception('testing');
299
+		$display = new Display();
300
+		$reflectedPathTrim = $this->getAccessibleMethod($display, 'getPathTrimStart');
301
+		$trimStart = $reflectedPathTrim->invokeArgs($display, array(getcwd(), __DIR__));
302
+		$reflectedTime = $this->getAccessibleMethod($display, 'getReadableTime');
303
+		$reflectedMemory = $this->getAccessibleMethod($display, 'getReadableMemory');
304
+
305
+		return array(
306
+			array(
307
+				'store' => array(
308
+					array(
309
+						'data' => 'testing message',
310
+						'type' => 'log'
311
+					),
312
+					array(
313
+						'name' => 'now',
314
+						'data' => microtime(true),
315
+						'type' => 'speed'
316
+					),
317
+					array(
318
+						'name' => 'little later',
319
+						'data' => microtime(true) + 1,
320
+						'type' => 'speed'
321
+					),
322
+					array(
323
+						'name' => 'invalid key',
324
+						'type' => 'foo'
325
+					)
326
+				),
327
+				'meta' => array(
328
+					'log'    => 1,
329
+					'memory' => 0,
330
+					'error'  => 1,
331
+					'speed'  => 2
332
+				),
333
+				'messages' => array(
334
+					array(
335
+						'message' => 'testing message',
336
+						'type'    => 'log'
337
+					),
338
+					array(
339
+						'message' => 'now',
340
+						'data'    => $reflectedTime->invokeArgs($display, array(microtime(true))),
341
+						'type'    => 'speed'
342
+					),
343
+					array(
344
+						'message' => 'little later',
345
+						'data'    => $reflectedTime->invokeArgs($display, array(microtime(true) + 1)),
346
+						'type'    => 'speed'
347
+					),
348
+					array(
349
+						'message' => 'Unrecognized console log type: foo',
350
+						'type'    => 'error'
351
+					)
352
+				)
353
+			),
354
+			array(
355
+				'store' => array(
356
+					array(
357
+						'data' => 'another testing message',
358
+						'type' => 'log'
359
+					),
360
+					array(
361
+						'name'      => 'test array',
362
+						'data'      => strlen(serialize(array('key' => 'value'))),
363
+						'data_type' => 'array',
364
+						'type'      => 'memory'
365
+					),
366
+					array(
367
+						'name'      => 'memory usage test',
368
+						'data'      => memory_get_usage(),
369
+						'data_type' => '',
370
+						'type'      => 'memory'
371
+					),
372
+					array(
373
+						'data' => $testException->getMessage(),
374
+						'file' => $testException->getFile(),
375
+						'line' => $testException->getLine(),
376
+						'type' => 'error'
377
+					)
378
+				),
379
+				'meta' => array(
380
+					'log'    => 1,
381
+					'memory' => 2,
382
+					'error'  => 1,
383
+					'speed'  => 0
384
+				),
385
+				'messages' => array(
386
+					array(
387
+						'message' => 'another testing message',
388
+						'type'    => 'log'
389
+					),
390
+					array(
391
+						'message' => 'array: test array',
392
+						'data'    => $reflectedMemory->invokeArgs(
393
+							$display,
394
+							array(strlen(serialize(array('key' => 'value'))))
395
+						),
396
+						'type'    => 'memory'
397
+					),
398
+					array(
399
+						'message' => 'memory usage test',
400
+						'data'    => $reflectedMemory->invokeArgs($display, array(memory_get_usage())),
401
+						'type'    => 'memory'
402
+					),
403
+					array(
404
+						'message' => sprintf(
405
+							'Line %s: %s in %s',
406
+							$testException->getLine(),
407
+							$testException->getMessage(),
408
+							substr($testException->getFile(), $trimStart)
409
+						),
410
+						'type'    => 'error'
411
+					)
412
+				)
413
+			)
414
+		);
415
+	}
416
+
417
+	public function dataPathTrimStart()
418
+	{
419
+		return array(
420
+			array(
421
+				'cwd' => '/Users/fakeUser/project',
422
+				'dir' => '/Users/fakeUser/project/vendor/particletree/pqp/tests/unit',
423
+				'expectedPosition' => 23,
424
+			),
425
+			array(
426
+				'cwd' => '/Users/fakeUser/project/public/path',
427
+				'dir' => '/Users/fakeUser/project/vendor/particletree/pqp/tests/unit',
428
+				'expectedPosition' => 24,
429
+			),
430
+		);
431
+	}
432
+
433
+	public function dataQueryData()
434
+	{
435
+		$display = new Display();
436
+		$reflectedTime = $this->getAccessibleMethod($display, 'getReadableTime');
437
+
438
+		return array(
439
+			array(
440
+				'data' => array(
441
+					array(
442
+						'sql'     => "SELECT * FROM testing",
443
+						'explain' => array('empty_key' => ''),
444
+						'time'    => 25
445
+					),
446
+					array(
447
+						'sql'     => "SELECT id FROM testing WHERE title = :title",
448
+						'explain' => array('key' => 'value'),
449
+						'time'    => 5
450
+					)
451
+				),
452
+				'meta' => array(
453
+					'count'   => 2,
454
+					'time'    => $reflectedTime->invokeArgs($display, array(30)),
455
+					'slowest' => $reflectedTime->invokeArgs($display, array(25)),
456
+				),
457
+				'list' => array(
458
+					array(
459
+						'message'  => 'SELECT * FROM testing',
460
+						'sub_data' => array(),
461
+						'data'     => $reflectedTime->invokeArgs($display, array(25))
462
+					),
463
+					array(
464
+						'message'  => 'SELECT id FROM testing WHERE title = :title',
465
+						'sub_data' => array('key' => 'value'),
466
+						'data'     => $reflectedTime->invokeArgs($display, array(5))
467
+					)
468
+				)
469
+			)
470
+		);
471
+	}
472
+
473
+	public function dataFileData()
474
+	{
475
+		$display = new Display();
476
+		$reflectedMemory = $this->getAccessibleMethod($display, 'getReadableMemory');
477
+
478
+		return array(
479
+			array(
480
+				'data' => array(
481
+					array(
482
+						'name' => getcwd() . '/test-file',
483
+						'size' => 1234
484
+					),
485
+					array(
486
+						'name' => getcwd() . '/test-file-2',
487
+						'size' => 66
488
+					)
489
+				),
490
+				'meta' => array(
491
+					'count'   => 2,
492
+					'size'    => $reflectedMemory->invokeArgs($display, array(1300)),
493
+					'largest' => $reflectedMemory->invokeArgs($display, array(1234)),
494
+				),
495
+				'list' => array(
496
+					array(
497
+						'message' => '/test-file',
498
+						'data'    => $reflectedMemory->invokeArgs($display, array(1234))
499
+					),
500
+					array(
501
+						'message' => '/test-file-2',
502
+						'data'    => $reflectedMemory->invokeArgs($display, array(66))
503
+					)
504
+				)
505
+			)
506
+		);
507
+	}
508
+
509
+	protected function setInternalProperty($class, $property, $value)
510
+	{
511
+		$reflectedClass = new ReflectionClass(get_class($class));
512
+		$reflectedProperty = $reflectedClass->getProperty($property);
513
+		$reflectedProperty->setAccessible(true);
514
+		$reflectedProperty->setValue($class, $value);
515
+	}
516
+
517
+	protected function getAccessibleMethod($class, $method)
518
+	{
519
+		$reflectedClass = new ReflectionClass(get_class($class));
520
+		$reflectedMethod = $reflectedClass->getMethod($method);
521
+		$reflectedMethod->setAccessible(true);
522
+		return $reflectedMethod;
523
+	}
524 524
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -277,15 +277,15 @@  discard block
 block discarded – undo
277 277
     public function testGetFilePath()
278 278
     {
279 279
         $display = new Display(array('relative_path' => false));
280
-        $path = getcwd() . '/puppies';
280
+        $path = getcwd().'/puppies';
281 281
         $reflectedFilePath = $this->getAccessibleMethod($display, 'getFilePath');
282 282
         $path = $reflectedFilePath->invokeArgs($display, array($path));
283
-        $expectedPath = getcwd() . '/puppies';
283
+        $expectedPath = getcwd().'/puppies';
284 284
 
285 285
         $this->assertEquals($expectedPath, $path);
286 286
 
287 287
         $display = new Display();
288
-        $path = getcwd() . '/puppies';
288
+        $path = getcwd().'/puppies';
289 289
         $reflectedFilePath = $this->getAccessibleMethod($display, 'getFilePath');
290 290
         $path = $reflectedFilePath->invokeArgs($display, array($path));
291 291
         $expectedPath = '/puppies';
@@ -479,11 +479,11 @@  discard block
 block discarded – undo
479 479
             array(
480 480
                 'data' => array(
481 481
                     array(
482
-                        'name' => getcwd() . '/test-file',
482
+                        'name' => getcwd().'/test-file',
483 483
                         'size' => 1234
484 484
                     ),
485 485
                     array(
486
-                        'name' => getcwd() . '/test-file-2',
486
+                        'name' => getcwd().'/test-file-2',
487 487
                         'size' => 66
488 488
                     )
489 489
                 ),
Please login to merge, or discard this patch.
src/Display.php 2 patches
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
                     break;
145 145
                 case 'memory':
146 146
                     $message = array(
147
-                        'message' => (!empty($log['data_type']) ? "{$log['data_type']}: " : '') . $log['name'],
147
+                        'message' => (!empty($log['data_type']) ? "{$log['data_type']}: " : '').$log['name'],
148 148
                         'data'    => $this->getReadableMemory($log['data']),
149 149
                         'type'    => 'memory'
150 150
                     );
@@ -195,11 +195,11 @@  discard block
 block discarded – undo
195 195
     public function getQueryMeta()
196 196
     {
197 197
         $queryCount = count($this->queryData);
198
-        $queryTotalTime = array_reduce($this->queryData, function ($sum, $row) {
198
+        $queryTotalTime = array_reduce($this->queryData, function($sum, $row) {
199 199
             return $sum + $row['time'];
200 200
         }, 0);
201 201
         $queryTotalTime = $this->getReadableTime($queryTotalTime);
202
-        $querySlowestTime = array_reduce($this->queryData, function ($slowest, $row) {
202
+        $querySlowestTime = array_reduce($this->queryData, function($slowest, $row) {
203 203
             return ($slowest < $row['time']) ? $row['time'] : $slowest;
204 204
         }, 0);
205 205
         $querySlowestTime = $this->getReadableTime($querySlowestTime);
@@ -247,11 +247,11 @@  discard block
 block discarded – undo
247 247
     protected function getFileMeta()
248 248
     {
249 249
         $fileCount = count($this->fileData);
250
-        $fileTotalSize = array_reduce($this->fileData, function ($sum, $row) {
250
+        $fileTotalSize = array_reduce($this->fileData, function($sum, $row) {
251 251
             return $sum + $row['size'];
252 252
         }, 0);
253 253
         $fileTotalSize = $this->getReadableMemory($fileTotalSize);
254
-        $fileLargestSize = array_reduce($this->fileData, function ($largest, $row) {
254
+        $fileLargestSize = array_reduce($this->fileData, function($largest, $row) {
255 255
             return ($largest < $row['size']) ? $row['size'] : $largest;
256 256
         }, 0);
257 257
         $fileLargestSize = $this->getReadableMemory($fileLargestSize);
@@ -325,7 +325,7 @@  discard block
 block discarded – undo
325 325
      */
326 326
     protected function filterMessages($messages, $type)
327 327
     {
328
-        return array_filter($messages, function ($message) use ($type) {
328
+        return array_filter($messages, function($message) use ($type) {
329 329
             return $message['type'] == $type;
330 330
         });
331 331
     }
@@ -381,12 +381,12 @@  discard block
 block discarded – undo
381 381
         $templateData = $this->gatherTemplateData();
382 382
 
383 383
         // todo is this really the best way to load these?
384
-        $styles = file_get_contents(__DIR__ . "/../{$this->options['style_path']}");
385
-        $script = file_get_contents(__DIR__ . "/../{$this->options['script_path']}");
384
+        $styles = file_get_contents(__DIR__."/../{$this->options['style_path']}");
385
+        $script = file_get_contents(__DIR__."/../{$this->options['script_path']}");
386 386
 
387
-        call_user_func(function () use ($templateData, $styles, $script) {
387
+        call_user_func(function() use ($templateData, $styles, $script) {
388 388
             extract($templateData);
389
-            require_once __DIR__ . '/../asset/display.html';
389
+            require_once __DIR__.'/../asset/display.html';
390 390
         });
391 391
     }
392 392
 }
Please login to merge, or discard this patch.
Indentation   +411 added lines, -411 removed lines patch added patch discarded remove patch
@@ -14,415 +14,415 @@
 block discarded – undo
14 14
 class Display
15 15
 {
16 16
 
17
-    /** @var  array */
18
-    protected $defaults = array(
19
-        'relative_path' => true,
20
-        'script_path' => 'asset/script.js',
21
-        'style_path' => 'asset/style.css'
22
-    );
23
-
24
-    /** @var  array */
25
-    protected $options;
26
-
27
-    /** @var  double */
28
-    protected $startTime;
29
-
30
-    /** @var  Console */
31
-    protected $console;
32
-
33
-    /** @var  array */
34
-    protected $speedData;
35
-
36
-    /** @var  array */
37
-    protected $queryData;
38
-
39
-    /** @var  array */
40
-    protected $memoryData;
41
-
42
-    /** @var  array */
43
-    protected $fileData;
44
-
45
-    /** @var  integer */
46
-    protected $pathTrimStart = 0;
47
-
48
-    /**
49
-     * @param array $options
50
-     */
51
-    public function __construct(array $options = array())
52
-    {
53
-        $options = array_intersect_key($options, $this->defaults);
54
-        $this->options = array_replace($this->defaults, $options);
55
-
56
-        if ($this->options['relative_path']) {
57
-            $this->pathTrimStart = $this->getPathTrimStart(getcwd(), __DIR__);
58
-        }
59
-    }
60
-
61
-    /**
62
-     * @param double $startTime
63
-     */
64
-    public function setStartTime($startTime)
65
-    {
66
-        $this->startTime = $startTime;
67
-    }
68
-
69
-    /**
70
-     * @param Console $console
71
-     */
72
-    public function setConsole(Console $console)
73
-    {
74
-        $this->console = $console;
75
-    }
76
-
77
-    /**
78
-     * Sets memory data
79
-     *
80
-     * @param array $data
81
-     */
82
-    public function setMemoryData(array $data)
83
-    {
84
-        $this->memoryData = $data;
85
-    }
86
-
87
-    /**
88
-     * Sets query data
89
-     *
90
-     * @param array $data
91
-     */
92
-    public function setQueryData(array $data)
93
-    {
94
-        $this->queryData = $data;
95
-    }
96
-
97
-    /**
98
-     * Sets speed data
99
-     *
100
-     * @param array $data
101
-     */
102
-    public function setSpeedData(array $data)
103
-    {
104
-        $this->speedData = $data;
105
-    }
106
-
107
-    /**
108
-     * Sets file data
109
-     *
110
-     * @param array $data
111
-     */
112
-    public function setFileData(array $data)
113
-    {
114
-        $this->fileData = $data;
115
-    }
116
-
117
-    /**
118
-     * @return integer
119
-     */
120
-    protected function getPathTrimStart($cwd, $dir)
121
-    {
122
-        for ($pos = 0; $pos <= strlen($cwd); $pos++) {
123
-            if (strncmp($cwd, $dir, $pos + 1) !== 0) {
124
-                break;
125
-            }
126
-        }
127
-
128
-        return $pos;
129
-    }
130
-
131
-    /**
132
-     * @return array
133
-     */
134
-    protected function getConsoleMeta()
135
-    {
136
-        $consoleMeta = array(
137
-            'log' => 0,
138
-            'memory' => 0,
139
-            'error' => 0,
140
-            'speed' => 0
141
-        );
142
-        foreach ($this->console->getLogs() as $log) {
143
-            if (array_key_exists($log['type'], $consoleMeta)) {
144
-                $consoleMeta[$log['type']]++;
145
-                continue;
146
-            }
147
-            $consoleMeta['error']++;
148
-        }
149
-
150
-        return $consoleMeta;
151
-    }
152
-
153
-    /**
154
-     * @return array
155
-     */
156
-    protected function getConsoleMessages()
157
-    {
158
-        $messages = array();
159
-        foreach ($this->console->getLogs() as $log) {
160
-            switch ($log['type']) {
161
-                case 'log':
162
-                    $message = array(
163
-                        'message' => print_r($log['data'], true),
164
-                        'type'    => 'log'
165
-                    );
166
-                    break;
167
-                case 'memory':
168
-                    $message = array(
169
-                        'message' => (!empty($log['data_type']) ? "{$log['data_type']}: " : '') . $log['name'],
170
-                        'data'    => $this->getReadableMemory($log['data']),
171
-                        'type'    => 'memory'
172
-                    );
173
-                    break;
174
-                case 'error':
175
-                    $message = array(
176
-                        'message' => "Line {$log['line']}: {$log['data']} in {$this->getFilePath($log['file'])}",
177
-                        'type'    => 'error'
178
-                    );
179
-                    break;
180
-                case 'speed':
181
-                    $elapsedTime = $log['data'] - $this->startTime;
182
-                    $message = array(
183
-                        'message' => $log['name'],
184
-                        'data'    => $this->getReadableTime($elapsedTime),
185
-                        'type'    => 'speed'
186
-                    );
187
-                    break;
188
-                default:
189
-                    $message = array(
190
-                        'message' => "Unrecognized console log type: {$log['type']}",
191
-                        'type'    => 'error'
192
-                    );
193
-                    break;
194
-            }
195
-            array_push($messages, $message);
196
-        }
197
-        return $messages;
198
-    }
199
-
200
-    /**
201
-     * @return array
202
-     */
203
-    protected function getSpeedMeta()
204
-    {
205
-        $elapsedTime = $this->getReadableTime($this->speedData['elapsed']);
206
-        $allowedTime = $this->getReadableTime($this->speedData['allowed'], 0);
207
-
208
-        return array(
209
-            'elapsed' => $elapsedTime,
210
-            'allowed' => $allowedTime,
211
-        );
212
-    }
213
-
214
-    /**
215
-     * @return array
216
-     */
217
-    public function getQueryMeta()
218
-    {
219
-        $queryCount = count($this->queryData);
220
-        $queryTotalTime = array_reduce($this->queryData, function ($sum, $row) {
221
-            return $sum + $row['time'];
222
-        }, 0);
223
-        $queryTotalTime = $this->getReadableTime($queryTotalTime);
224
-        $querySlowestTime = array_reduce($this->queryData, function ($slowest, $row) {
225
-            return ($slowest < $row['time']) ? $row['time'] : $slowest;
226
-        }, 0);
227
-        $querySlowestTime = $this->getReadableTime($querySlowestTime);
228
-
229
-        return array(
230
-            'count'   => $queryCount,
231
-            'time'    => $queryTotalTime,
232
-            'slowest' => $querySlowestTime
233
-        );
234
-    }
235
-
236
-    /**
237
-     * @return array
238
-     */
239
-    public function getQueryList()
240
-    {
241
-        $queryList = array();
242
-        foreach ($this->queryData as $query) {
243
-            array_push($queryList, array(
244
-                'message'  => $query['sql'],
245
-                'sub_data' => array_filter($query['explain']),
246
-                'data'     => $this->getReadableTime($query['time'])
247
-            ));
248
-        }
249
-        return $queryList;
250
-    }
251
-
252
-    /**
253
-     * @return array
254
-     */
255
-    public function getMemoryMeta()
256
-    {
257
-        $usedMemory = $this->getReadableMemory($this->memoryData['used']);
258
-        $allowedMemory = $this->memoryData['allowed']; // todo parse this, maybe?
259
-
260
-        return array(
261
-            'used'    => $usedMemory,
262
-            'allowed' => $allowedMemory
263
-        );
264
-    }
265
-
266
-    /**
267
-     * @return array
268
-     */
269
-    protected function getFileMeta()
270
-    {
271
-        $fileCount = count($this->fileData);
272
-        $fileTotalSize = array_reduce($this->fileData, function ($sum, $row) {
273
-            return $sum + $row['size'];
274
-        }, 0);
275
-        $fileTotalSize = $this->getReadableMemory($fileTotalSize);
276
-        $fileLargestSize = array_reduce($this->fileData, function ($largest, $row) {
277
-            return ($largest < $row['size']) ? $row['size'] : $largest;
278
-        }, 0);
279
-        $fileLargestSize = $this->getReadableMemory($fileLargestSize);
280
-
281
-        return array(
282
-            'count' => $fileCount,
283
-            'size' => $fileTotalSize,
284
-            'largest' => $fileLargestSize
285
-        );
286
-    }
287
-
288
-    /**
289
-     * @return array
290
-     */
291
-    protected function getFileList()
292
-    {
293
-        $fileList = array();
294
-        foreach ($this->fileData as $file) {
295
-            array_push($fileList, array(
296
-                'message' => $this->getFilePath($file['name']),
297
-                'data'    => $this->getReadableMemory($file['size'])
298
-            ));
299
-        }
300
-        return $fileList;
301
-    }
302
-
303
-    /**
304
-     * Formatter for human-readable time
305
-     * Only handles time up to 60 minutes gracefully
306
-     *
307
-     * @param double  $time
308
-     * @param integer $percision
309
-     * @return string
310
-     */
311
-    protected function getReadableTime($time, $percision = 3)
312
-    {
313
-        $unit = 's';
314
-        if ($time < 1) {
315
-            $time *= 1000;
316
-            $percision = 0;
317
-            $unit = 'ms';
318
-        } elseif ($time > 60) {
319
-            $time /= 60;
320
-            $unit = 'm';
321
-        }
322
-        $time = number_format($time, $percision);
323
-        return "{$time} {$unit}";
324
-    }
325
-
326
-    /**
327
-     * Formatter for human-readable memory
328
-     * Only handles time up to a few gigs gracefully
329
-     *
330
-     * @param double  $size
331
-     * @param integer $percision
332
-     */
333
-    protected function getReadableMemory($size, $percision = 2)
334
-    {
335
-        $unitOptions = array('b', 'k', 'M', 'G');
336
-
337
-        $base = log($size, 1024);
338
-
339
-        $memory = round(pow(1024, $base - floor($base)), $percision);
340
-        $unit = $unitOptions[floor($base)];
341
-        return "{$memory} {$unit}";
342
-    }
343
-
344
-    /**
345
-     * @param string $path
346
-     * @return string
347
-     */
348
-    protected function getFilePath($path)
349
-    {
350
-        if (!$this->options['relative_path']) {
351
-            return $path;
352
-        }
353
-
354
-        return substr($path, $this->pathTrimStart);
355
-    }
356
-
357
-    /**
358
-     * @param array  $messages
359
-     * @param string $type
360
-     * @return array
361
-     */
362
-    protected function filterMessages($messages, $type)
363
-    {
364
-        return array_filter($messages, function ($message) use ($type) {
365
-            return $message['type'] == $type;
366
-        });
367
-    }
368
-
369
-    /**
370
-     * @returns array
371
-     */
372
-    protected function gatherTemplateData()
373
-    {
374
-        $consoleMeta = $this->getConsoleMeta();
375
-        $speedMeta = $this->getSpeedMeta();
376
-        $queryMeta = $this->getQueryMeta();
377
-        $memoryMeta = $this->getMemoryMeta();
378
-        $fileMeta = $this->getFileMeta();
379
-
380
-        $consoleMessages = $this->getConsoleMessages();
381
-        $queryList = $this->getQueryList();
382
-        $fileList = $this->getFileList();
383
-
384
-        return array(
385
-            'header' => array(
386
-                'console' => array_sum($consoleMeta),
387
-                'speed'   => $speedMeta['elapsed'],
388
-                'query'   => $queryMeta['count'],
389
-                'memory'  => $memoryMeta['used'],
390
-                'files'   => $fileMeta['count']
391
-            ),
392
-            'console' => array(
393
-                'meta' => $consoleMeta,
394
-                'messages' => $consoleMessages
395
-            ),
396
-            'speed' => array(
397
-                'meta' => $speedMeta,
398
-                'messages' => $this->filterMessages($consoleMessages, 'speed')
399
-            ),
400
-            'query' => array(
401
-                'meta' => $queryMeta,
402
-                'messages' => $queryList
403
-            ),
404
-            'memory' => array(
405
-                'meta' => $memoryMeta,
406
-                'messages' => $this->filterMessages($consoleMessages, 'memory')
407
-            ),
408
-            'files' => array(
409
-                'meta' => $fileMeta,
410
-                'messages' => $fileList
411
-            )
412
-        );
413
-    }
414
-
415
-    public function __invoke()
416
-    {
417
-        $templateData = $this->gatherTemplateData();
418
-
419
-        // todo is this really the best way to load these?
420
-        $styles = file_get_contents(__DIR__ . "/../{$this->options['style_path']}");
421
-        $script = file_get_contents(__DIR__ . "/../{$this->options['script_path']}");
422
-
423
-        call_user_func(function () use ($templateData, $styles, $script) {
424
-            extract($templateData);
425
-            require_once __DIR__ . '/../asset/display.html';
426
-        });
427
-    }
17
+	/** @var  array */
18
+	protected $defaults = array(
19
+		'relative_path' => true,
20
+		'script_path' => 'asset/script.js',
21
+		'style_path' => 'asset/style.css'
22
+	);
23
+
24
+	/** @var  array */
25
+	protected $options;
26
+
27
+	/** @var  double */
28
+	protected $startTime;
29
+
30
+	/** @var  Console */
31
+	protected $console;
32
+
33
+	/** @var  array */
34
+	protected $speedData;
35
+
36
+	/** @var  array */
37
+	protected $queryData;
38
+
39
+	/** @var  array */
40
+	protected $memoryData;
41
+
42
+	/** @var  array */
43
+	protected $fileData;
44
+
45
+	/** @var  integer */
46
+	protected $pathTrimStart = 0;
47
+
48
+	/**
49
+	 * @param array $options
50
+	 */
51
+	public function __construct(array $options = array())
52
+	{
53
+		$options = array_intersect_key($options, $this->defaults);
54
+		$this->options = array_replace($this->defaults, $options);
55
+
56
+		if ($this->options['relative_path']) {
57
+			$this->pathTrimStart = $this->getPathTrimStart(getcwd(), __DIR__);
58
+		}
59
+	}
60
+
61
+	/**
62
+	 * @param double $startTime
63
+	 */
64
+	public function setStartTime($startTime)
65
+	{
66
+		$this->startTime = $startTime;
67
+	}
68
+
69
+	/**
70
+	 * @param Console $console
71
+	 */
72
+	public function setConsole(Console $console)
73
+	{
74
+		$this->console = $console;
75
+	}
76
+
77
+	/**
78
+	 * Sets memory data
79
+	 *
80
+	 * @param array $data
81
+	 */
82
+	public function setMemoryData(array $data)
83
+	{
84
+		$this->memoryData = $data;
85
+	}
86
+
87
+	/**
88
+	 * Sets query data
89
+	 *
90
+	 * @param array $data
91
+	 */
92
+	public function setQueryData(array $data)
93
+	{
94
+		$this->queryData = $data;
95
+	}
96
+
97
+	/**
98
+	 * Sets speed data
99
+	 *
100
+	 * @param array $data
101
+	 */
102
+	public function setSpeedData(array $data)
103
+	{
104
+		$this->speedData = $data;
105
+	}
106
+
107
+	/**
108
+	 * Sets file data
109
+	 *
110
+	 * @param array $data
111
+	 */
112
+	public function setFileData(array $data)
113
+	{
114
+		$this->fileData = $data;
115
+	}
116
+
117
+	/**
118
+	 * @return integer
119
+	 */
120
+	protected function getPathTrimStart($cwd, $dir)
121
+	{
122
+		for ($pos = 0; $pos <= strlen($cwd); $pos++) {
123
+			if (strncmp($cwd, $dir, $pos + 1) !== 0) {
124
+				break;
125
+			}
126
+		}
127
+
128
+		return $pos;
129
+	}
130
+
131
+	/**
132
+	 * @return array
133
+	 */
134
+	protected function getConsoleMeta()
135
+	{
136
+		$consoleMeta = array(
137
+			'log' => 0,
138
+			'memory' => 0,
139
+			'error' => 0,
140
+			'speed' => 0
141
+		);
142
+		foreach ($this->console->getLogs() as $log) {
143
+			if (array_key_exists($log['type'], $consoleMeta)) {
144
+				$consoleMeta[$log['type']]++;
145
+				continue;
146
+			}
147
+			$consoleMeta['error']++;
148
+		}
149
+
150
+		return $consoleMeta;
151
+	}
152
+
153
+	/**
154
+	 * @return array
155
+	 */
156
+	protected function getConsoleMessages()
157
+	{
158
+		$messages = array();
159
+		foreach ($this->console->getLogs() as $log) {
160
+			switch ($log['type']) {
161
+				case 'log':
162
+					$message = array(
163
+						'message' => print_r($log['data'], true),
164
+						'type'    => 'log'
165
+					);
166
+					break;
167
+				case 'memory':
168
+					$message = array(
169
+						'message' => (!empty($log['data_type']) ? "{$log['data_type']}: " : '') . $log['name'],
170
+						'data'    => $this->getReadableMemory($log['data']),
171
+						'type'    => 'memory'
172
+					);
173
+					break;
174
+				case 'error':
175
+					$message = array(
176
+						'message' => "Line {$log['line']}: {$log['data']} in {$this->getFilePath($log['file'])}",
177
+						'type'    => 'error'
178
+					);
179
+					break;
180
+				case 'speed':
181
+					$elapsedTime = $log['data'] - $this->startTime;
182
+					$message = array(
183
+						'message' => $log['name'],
184
+						'data'    => $this->getReadableTime($elapsedTime),
185
+						'type'    => 'speed'
186
+					);
187
+					break;
188
+				default:
189
+					$message = array(
190
+						'message' => "Unrecognized console log type: {$log['type']}",
191
+						'type'    => 'error'
192
+					);
193
+					break;
194
+			}
195
+			array_push($messages, $message);
196
+		}
197
+		return $messages;
198
+	}
199
+
200
+	/**
201
+	 * @return array
202
+	 */
203
+	protected function getSpeedMeta()
204
+	{
205
+		$elapsedTime = $this->getReadableTime($this->speedData['elapsed']);
206
+		$allowedTime = $this->getReadableTime($this->speedData['allowed'], 0);
207
+
208
+		return array(
209
+			'elapsed' => $elapsedTime,
210
+			'allowed' => $allowedTime,
211
+		);
212
+	}
213
+
214
+	/**
215
+	 * @return array
216
+	 */
217
+	public function getQueryMeta()
218
+	{
219
+		$queryCount = count($this->queryData);
220
+		$queryTotalTime = array_reduce($this->queryData, function ($sum, $row) {
221
+			return $sum + $row['time'];
222
+		}, 0);
223
+		$queryTotalTime = $this->getReadableTime($queryTotalTime);
224
+		$querySlowestTime = array_reduce($this->queryData, function ($slowest, $row) {
225
+			return ($slowest < $row['time']) ? $row['time'] : $slowest;
226
+		}, 0);
227
+		$querySlowestTime = $this->getReadableTime($querySlowestTime);
228
+
229
+		return array(
230
+			'count'   => $queryCount,
231
+			'time'    => $queryTotalTime,
232
+			'slowest' => $querySlowestTime
233
+		);
234
+	}
235
+
236
+	/**
237
+	 * @return array
238
+	 */
239
+	public function getQueryList()
240
+	{
241
+		$queryList = array();
242
+		foreach ($this->queryData as $query) {
243
+			array_push($queryList, array(
244
+				'message'  => $query['sql'],
245
+				'sub_data' => array_filter($query['explain']),
246
+				'data'     => $this->getReadableTime($query['time'])
247
+			));
248
+		}
249
+		return $queryList;
250
+	}
251
+
252
+	/**
253
+	 * @return array
254
+	 */
255
+	public function getMemoryMeta()
256
+	{
257
+		$usedMemory = $this->getReadableMemory($this->memoryData['used']);
258
+		$allowedMemory = $this->memoryData['allowed']; // todo parse this, maybe?
259
+
260
+		return array(
261
+			'used'    => $usedMemory,
262
+			'allowed' => $allowedMemory
263
+		);
264
+	}
265
+
266
+	/**
267
+	 * @return array
268
+	 */
269
+	protected function getFileMeta()
270
+	{
271
+		$fileCount = count($this->fileData);
272
+		$fileTotalSize = array_reduce($this->fileData, function ($sum, $row) {
273
+			return $sum + $row['size'];
274
+		}, 0);
275
+		$fileTotalSize = $this->getReadableMemory($fileTotalSize);
276
+		$fileLargestSize = array_reduce($this->fileData, function ($largest, $row) {
277
+			return ($largest < $row['size']) ? $row['size'] : $largest;
278
+		}, 0);
279
+		$fileLargestSize = $this->getReadableMemory($fileLargestSize);
280
+
281
+		return array(
282
+			'count' => $fileCount,
283
+			'size' => $fileTotalSize,
284
+			'largest' => $fileLargestSize
285
+		);
286
+	}
287
+
288
+	/**
289
+	 * @return array
290
+	 */
291
+	protected function getFileList()
292
+	{
293
+		$fileList = array();
294
+		foreach ($this->fileData as $file) {
295
+			array_push($fileList, array(
296
+				'message' => $this->getFilePath($file['name']),
297
+				'data'    => $this->getReadableMemory($file['size'])
298
+			));
299
+		}
300
+		return $fileList;
301
+	}
302
+
303
+	/**
304
+	 * Formatter for human-readable time
305
+	 * Only handles time up to 60 minutes gracefully
306
+	 *
307
+	 * @param double  $time
308
+	 * @param integer $percision
309
+	 * @return string
310
+	 */
311
+	protected function getReadableTime($time, $percision = 3)
312
+	{
313
+		$unit = 's';
314
+		if ($time < 1) {
315
+			$time *= 1000;
316
+			$percision = 0;
317
+			$unit = 'ms';
318
+		} elseif ($time > 60) {
319
+			$time /= 60;
320
+			$unit = 'm';
321
+		}
322
+		$time = number_format($time, $percision);
323
+		return "{$time} {$unit}";
324
+	}
325
+
326
+	/**
327
+	 * Formatter for human-readable memory
328
+	 * Only handles time up to a few gigs gracefully
329
+	 *
330
+	 * @param double  $size
331
+	 * @param integer $percision
332
+	 */
333
+	protected function getReadableMemory($size, $percision = 2)
334
+	{
335
+		$unitOptions = array('b', 'k', 'M', 'G');
336
+
337
+		$base = log($size, 1024);
338
+
339
+		$memory = round(pow(1024, $base - floor($base)), $percision);
340
+		$unit = $unitOptions[floor($base)];
341
+		return "{$memory} {$unit}";
342
+	}
343
+
344
+	/**
345
+	 * @param string $path
346
+	 * @return string
347
+	 */
348
+	protected function getFilePath($path)
349
+	{
350
+		if (!$this->options['relative_path']) {
351
+			return $path;
352
+		}
353
+
354
+		return substr($path, $this->pathTrimStart);
355
+	}
356
+
357
+	/**
358
+	 * @param array  $messages
359
+	 * @param string $type
360
+	 * @return array
361
+	 */
362
+	protected function filterMessages($messages, $type)
363
+	{
364
+		return array_filter($messages, function ($message) use ($type) {
365
+			return $message['type'] == $type;
366
+		});
367
+	}
368
+
369
+	/**
370
+	 * @returns array
371
+	 */
372
+	protected function gatherTemplateData()
373
+	{
374
+		$consoleMeta = $this->getConsoleMeta();
375
+		$speedMeta = $this->getSpeedMeta();
376
+		$queryMeta = $this->getQueryMeta();
377
+		$memoryMeta = $this->getMemoryMeta();
378
+		$fileMeta = $this->getFileMeta();
379
+
380
+		$consoleMessages = $this->getConsoleMessages();
381
+		$queryList = $this->getQueryList();
382
+		$fileList = $this->getFileList();
383
+
384
+		return array(
385
+			'header' => array(
386
+				'console' => array_sum($consoleMeta),
387
+				'speed'   => $speedMeta['elapsed'],
388
+				'query'   => $queryMeta['count'],
389
+				'memory'  => $memoryMeta['used'],
390
+				'files'   => $fileMeta['count']
391
+			),
392
+			'console' => array(
393
+				'meta' => $consoleMeta,
394
+				'messages' => $consoleMessages
395
+			),
396
+			'speed' => array(
397
+				'meta' => $speedMeta,
398
+				'messages' => $this->filterMessages($consoleMessages, 'speed')
399
+			),
400
+			'query' => array(
401
+				'meta' => $queryMeta,
402
+				'messages' => $queryList
403
+			),
404
+			'memory' => array(
405
+				'meta' => $memoryMeta,
406
+				'messages' => $this->filterMessages($consoleMessages, 'memory')
407
+			),
408
+			'files' => array(
409
+				'meta' => $fileMeta,
410
+				'messages' => $fileList
411
+			)
412
+		);
413
+	}
414
+
415
+	public function __invoke()
416
+	{
417
+		$templateData = $this->gatherTemplateData();
418
+
419
+		// todo is this really the best way to load these?
420
+		$styles = file_get_contents(__DIR__ . "/../{$this->options['style_path']}");
421
+		$script = file_get_contents(__DIR__ . "/../{$this->options['script_path']}");
422
+
423
+		call_user_func(function () use ($templateData, $styles, $script) {
424
+			extract($templateData);
425
+			require_once __DIR__ . '/../asset/display.html';
426
+		});
427
+	}
428 428
 }
Please login to merge, or discard this patch.
src/Console.php 1 patch
Indentation   +85 added lines, -85 removed lines patch added patch discarded remove patch
@@ -15,97 +15,97 @@
 block discarded – undo
15 15
 class Console
16 16
 {
17 17
 
18
-    /** @var  array */
19
-    protected $store = array();
18
+	/** @var  array */
19
+	protected $store = array();
20 20
 
21
-    /**
22
-     * Logs data to the console
23
-     * Accepts any data type
24
-     *
25
-     * @param mixed $data
26
-     */
27
-    public function log($data)
28
-    {
29
-        array_push($this->store, array(
30
-          'data' => $data,
31
-          'type' => 'log'
32
-        ));
33
-    }
21
+	/**
22
+	 * Logs data to the console
23
+	 * Accepts any data type
24
+	 *
25
+	 * @param mixed $data
26
+	 */
27
+	public function log($data)
28
+	{
29
+		array_push($this->store, array(
30
+		  'data' => $data,
31
+		  'type' => 'log'
32
+		));
33
+	}
34 34
 
35
-    /**
36
-     * Logs memory usage of a variable
37
-     * If no parameter is passed in, logs current memory usage
38
-     *
39
-     * @param mixed $object
40
-     * @param string $name
41
-     * @param boolean $literal
42
-     */
43
-    public function logMemory($object = null, $name = 'PHP', $literal = false)
44
-    {
45
-        $memory = memory_get_usage();
46
-        $dataType = '';
47
-        if (!is_null($object) && !$literal) {
48
-            $memory = strlen(serialize($object));
49
-            $dataType = gettype($object);
50
-        } else if (is_numeric($object) && $literal) {
51
-            $memory = floatval($object);
52
-        }
35
+	/**
36
+	 * Logs memory usage of a variable
37
+	 * If no parameter is passed in, logs current memory usage
38
+	 *
39
+	 * @param mixed $object
40
+	 * @param string $name
41
+	 * @param boolean $literal
42
+	 */
43
+	public function logMemory($object = null, $name = 'PHP', $literal = false)
44
+	{
45
+		$memory = memory_get_usage();
46
+		$dataType = '';
47
+		if (!is_null($object) && !$literal) {
48
+			$memory = strlen(serialize($object));
49
+			$dataType = gettype($object);
50
+		} else if (is_numeric($object) && $literal) {
51
+			$memory = floatval($object);
52
+		}
53 53
 
54
-        array_push($this->store, array(
55
-            'name'      => $name,
56
-            'data'      => $memory,
57
-            'data_type' => $dataType,
58
-            'type'      => 'memory'
59
-        ));
60
-    }
54
+		array_push($this->store, array(
55
+			'name'      => $name,
56
+			'data'      => $memory,
57
+			'data_type' => $dataType,
58
+			'type'      => 'memory'
59
+		));
60
+	}
61 61
 
62
-    /**
63
-     * Logs exception with optional message override
64
-     *
65
-     * @param Exception $exception
66
-     * @param string    $message
67
-     */
68
-    public function logError(Exception $exception, $message = '')
69
-    {
70
-        if (empty($message)) {
71
-            $message = $exception->getMessage();
72
-        }
62
+	/**
63
+	 * Logs exception with optional message override
64
+	 *
65
+	 * @param Exception $exception
66
+	 * @param string    $message
67
+	 */
68
+	public function logError(Exception $exception, $message = '')
69
+	{
70
+		if (empty($message)) {
71
+			$message = $exception->getMessage();
72
+		}
73 73
 
74
-        array_push($this->store, array(
75
-            'data' => $message,
76
-            'file' => $exception->getFile(),
77
-            'line' => $exception->getLine(),
78
-            'type' => 'error'
79
-        ));
80
-    }
74
+		array_push($this->store, array(
75
+			'data' => $message,
76
+			'file' => $exception->getFile(),
77
+			'line' => $exception->getLine(),
78
+			'type' => 'error'
79
+		));
80
+	}
81 81
 
82
-    /**
83
-     * Logs current time with optional message
84
-     *
85
-     * @param string $name
86
-     * @param float  $literalTime
87
-     */
88
-    public function logSpeed($name = 'Point in Time', $literalTime = null)
89
-    {
90
-        $time = microtime(true);
91
-        if (!is_null($literalTime) && is_float($literalTime)) {
92
-            $time = $literalTime;
93
-        }
82
+	/**
83
+	 * Logs current time with optional message
84
+	 *
85
+	 * @param string $name
86
+	 * @param float  $literalTime
87
+	 */
88
+	public function logSpeed($name = 'Point in Time', $literalTime = null)
89
+	{
90
+		$time = microtime(true);
91
+		if (!is_null($literalTime) && is_float($literalTime)) {
92
+			$time = $literalTime;
93
+		}
94 94
 
95
-        array_push($this->store, array(
96
-            'data' => $time,
97
-            'name' => $name,
98
-            'type' => 'speed'
99
-        ));
100
-    }
95
+		array_push($this->store, array(
96
+			'data' => $time,
97
+			'name' => $name,
98
+			'type' => 'speed'
99
+		));
100
+	}
101 101
 
102
-    /**
103
-     * Returns the collected logs
104
-     *
105
-     * @returns array
106
-     */
107
-    public function getLogs()
108
-    {
109
-        return $this->store;
110
-    }
102
+	/**
103
+	 * Returns the collected logs
104
+	 *
105
+	 * @returns array
106
+	 */
107
+	public function getLogs()
108
+	{
109
+		return $this->store;
110
+	}
111 111
 }
Please login to merge, or discard this patch.
tests/unit/ConsoleTest.php 1 patch
Indentation   +124 added lines, -124 removed lines patch added patch discarded remove patch
@@ -9,128 +9,128 @@
 block discarded – undo
9 9
 class ConsoleTest extends PHPUnit_Framework_TestCase
10 10
 {
11 11
 
12
-    public function testLog()
13
-    {
14
-        $data = array(
15
-            'key' => 'value'
16
-        );
17
-
18
-        $console = new Console();
19
-        $console->log($data);
20
-        $store = $this->getProtectedStore($console);
21
-        $log = array_pop($store);
22
-
23
-        $this->assertSame($data, $log['data']);
24
-        $this->assertEquals('log', $log['type']);
25
-    }
26
-
27
-    public function testLogMemory()
28
-    {
29
-        $data = array(
30
-            'key' => 'value'
31
-        );
32
-        $memory = strlen(serialize($data));
33
-        $name = 'Test Array';
34
-
35
-        $console = new Console();
36
-        $console->logMemory($data, $name);
37
-        $store = $this->getProtectedStore($console);
38
-        $log = array_pop($store);
39
-
40
-        $this->assertEquals($name, $log['name']);
41
-        $this->assertEquals($memory, $log['data']);
42
-        $this->assertEquals('array', $log['data_type']);
43
-        $this->assertEquals('memory', $log['type']);
44
-
45
-        $data = '12345';
46
-
47
-        $console = new Console();
48
-        $console->logMemory($data, 'PHP', true);
49
-        $store = $this->getProtectedStore($console);
50
-        $log = array_pop($store);
51
-
52
-        $this->assertEquals($data, $log['data']);
53
-    }
54
-
55
-    public function testLogError()
56
-    {
57
-        $error = new Exception('Test Exception');
58
-
59
-        $console = new Console();
60
-        $console->logError($error);
61
-        $store = $this->getProtectedStore($console);
62
-        $log = array_pop($store);
63
-
64
-        $this->assertEquals($error->getMessage(), $log['data']);
65
-        $this->assertEquals($error->getFile(), $log['file']);
66
-        $this->assertEquals($error->getLine(), $log['line']);
67
-        $this->assertEquals('error', $log['type']);
68
-
69
-        $error = new Exception('Test Exception');
70
-        $message = 'override message';
71
-
72
-        $console = new Console();
73
-        $console->logError($error, $message);
74
-        $store = $this->getProtectedStore($console);
75
-        $log = array_pop($store);
76
-
77
-        $this->assertEquals($message, $log['data']);
78
-    }
79
-
80
-    public function testLogSpeed()
81
-    {
82
-        $name = 'Test Speed';
83
-
84
-        $console = new Console();
85
-        $console->logSpeed($name);
86
-        $store = $this->getProtectedStore($console);
87
-        $log = array_pop($store);
88
-
89
-        $this->assertEquals($name, $log['name']);
90
-        $this->assertEquals('speed', $log['type']);
91
-
92
-        $name = 'Literal Time';
93
-        $time = 12345.1231;
94
-
95
-        $console = new Console();
96
-        $console->logSpeed($name, $time);
97
-        $store = $this->getProtectedStore($console);
98
-        $log = array_pop($store);
99
-
100
-        $this->assertEquals($name, $log['name']);
101
-        $this->assertEquals($time, $log['data']);
102
-    }
103
-
104
-    public function testGetLogs()
105
-    {
106
-        $store = array(
107
-            array(
108
-                'data' => 'a string',
109
-                'type' => 'log'
110
-            ),
111
-            array(
112
-                'name' => '',
113
-                'data' => 123,
114
-                'data_type' => 'array',
115
-                'type' => 'memory'
116
-            )
117
-        );
118
-
119
-        $console = new Console();
120
-
121
-        $reflectedConsole = new ReflectionClass(get_class($console));
122
-        $reflectedProperty = $reflectedConsole->getProperty('store');
123
-        $reflectedProperty->setAccessible(true);
124
-        $reflectedProperty->setValue($console, $store);
125
-
126
-        $this->assertSame($store, $console->getLogs());
127
-    }
128
-
129
-    protected function getProtectedStore(Console $console)
130
-    {
131
-        $reflectedConsole = new ReflectionClass(get_class($console));
132
-        $reflectedProperty = $reflectedConsole->getProperty('store');
133
-        $reflectedProperty->setAccessible(true);
134
-        return $reflectedProperty->getValue($console);
135
-    }
12
+	public function testLog()
13
+	{
14
+		$data = array(
15
+			'key' => 'value'
16
+		);
17
+
18
+		$console = new Console();
19
+		$console->log($data);
20
+		$store = $this->getProtectedStore($console);
21
+		$log = array_pop($store);
22
+
23
+		$this->assertSame($data, $log['data']);
24
+		$this->assertEquals('log', $log['type']);
25
+	}
26
+
27
+	public function testLogMemory()
28
+	{
29
+		$data = array(
30
+			'key' => 'value'
31
+		);
32
+		$memory = strlen(serialize($data));
33
+		$name = 'Test Array';
34
+
35
+		$console = new Console();
36
+		$console->logMemory($data, $name);
37
+		$store = $this->getProtectedStore($console);
38
+		$log = array_pop($store);
39
+
40
+		$this->assertEquals($name, $log['name']);
41
+		$this->assertEquals($memory, $log['data']);
42
+		$this->assertEquals('array', $log['data_type']);
43
+		$this->assertEquals('memory', $log['type']);
44
+
45
+		$data = '12345';
46
+
47
+		$console = new Console();
48
+		$console->logMemory($data, 'PHP', true);
49
+		$store = $this->getProtectedStore($console);
50
+		$log = array_pop($store);
51
+
52
+		$this->assertEquals($data, $log['data']);
53
+	}
54
+
55
+	public function testLogError()
56
+	{
57
+		$error = new Exception('Test Exception');
58
+
59
+		$console = new Console();
60
+		$console->logError($error);
61
+		$store = $this->getProtectedStore($console);
62
+		$log = array_pop($store);
63
+
64
+		$this->assertEquals($error->getMessage(), $log['data']);
65
+		$this->assertEquals($error->getFile(), $log['file']);
66
+		$this->assertEquals($error->getLine(), $log['line']);
67
+		$this->assertEquals('error', $log['type']);
68
+
69
+		$error = new Exception('Test Exception');
70
+		$message = 'override message';
71
+
72
+		$console = new Console();
73
+		$console->logError($error, $message);
74
+		$store = $this->getProtectedStore($console);
75
+		$log = array_pop($store);
76
+
77
+		$this->assertEquals($message, $log['data']);
78
+	}
79
+
80
+	public function testLogSpeed()
81
+	{
82
+		$name = 'Test Speed';
83
+
84
+		$console = new Console();
85
+		$console->logSpeed($name);
86
+		$store = $this->getProtectedStore($console);
87
+		$log = array_pop($store);
88
+
89
+		$this->assertEquals($name, $log['name']);
90
+		$this->assertEquals('speed', $log['type']);
91
+
92
+		$name = 'Literal Time';
93
+		$time = 12345.1231;
94
+
95
+		$console = new Console();
96
+		$console->logSpeed($name, $time);
97
+		$store = $this->getProtectedStore($console);
98
+		$log = array_pop($store);
99
+
100
+		$this->assertEquals($name, $log['name']);
101
+		$this->assertEquals($time, $log['data']);
102
+	}
103
+
104
+	public function testGetLogs()
105
+	{
106
+		$store = array(
107
+			array(
108
+				'data' => 'a string',
109
+				'type' => 'log'
110
+			),
111
+			array(
112
+				'name' => '',
113
+				'data' => 123,
114
+				'data_type' => 'array',
115
+				'type' => 'memory'
116
+			)
117
+		);
118
+
119
+		$console = new Console();
120
+
121
+		$reflectedConsole = new ReflectionClass(get_class($console));
122
+		$reflectedProperty = $reflectedConsole->getProperty('store');
123
+		$reflectedProperty->setAccessible(true);
124
+		$reflectedProperty->setValue($console, $store);
125
+
126
+		$this->assertSame($store, $console->getLogs());
127
+	}
128
+
129
+	protected function getProtectedStore(Console $console)
130
+	{
131
+		$reflectedConsole = new ReflectionClass(get_class($console));
132
+		$reflectedProperty = $reflectedConsole->getProperty('store');
133
+		$reflectedProperty->setAccessible(true);
134
+		return $reflectedProperty->getValue($console);
135
+	}
136 136
 }
Please login to merge, or discard this patch.