GenericProfiler::getData()   B
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 27
rs 8.8571
cc 3
eloc 18
nc 4
nop 0
1
<?php
2
/*
3
 * This file is part of Yolk - Gamer Network's PHP Framework.
4
 *
5
 * Copyright (c) 2014 Gamer Network Ltd.
6
 *
7
 * Distributed under the MIT License, a copy of which is available in the
8
 * LICENSE file that was bundled with this package, or online at:
9
 * https://github.com/gamernetwork/yolk-profiler
10
 */
11
12
namespace yolk\profiler;
13
14
use yolk\contracts\profiler\Profiler;
15
use yolk\contracts\profiler\Timer;
16
17
use yolk\contracts\support\Dumpable;
18
use yolk\contracts\support\Arrayable;
19
20
/**
21
 * Simple profiler class for recording code execution time, memory usage and database queries.
22
 */
23
class GenericProfiler implements Profiler, Dumpable {
24
25
	/**
26
	 * Array of timer instances.
27
	 * @var Timer[]
28
	 */
29
	protected $timers;
30
31
	/**
32
	 * Array of mark instances.
33
	 * @var Mark[]
34
	 */
35
	protected $marks;
36
37
	/**
38
	 * Array of query information.
39
	 * @var array
40
	 */
41
	protected $queries;
42
43
	/**
44
	 * Key/value store of additional data.
45
	 * @var array
46
	 */
47
	protected $meta;
48
49
	protected $config;
50
51
	public function __construct( $time = null, $memory = null ) {
52
		$this->reset($time, $memory);
53
	}
54
55
	public function reset( $time = null, $memory = null ) {
56
57
		$memory = isset($memory) ? $memory : memory_get_usage();
58
59
		// create and start internal timer
60
		$this->timers = [
0 ignored issues
show
Documentation Bug introduced by
It seems like array('' => new \yolk\profiler\GenericTimer()) of type array<string,object<yolk...filer\\GenericTimer>"}> is incompatible with the declared type array<integer,object<yol...tracts\profiler\Timer>> of property $timers.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
61
			'' => new GenericTimer()
62
		];
63
64
		$this->timers['']->start($time);
65
66
		$this->marks['start'] = new Mark(
67
			'start',
68
			0,
69
			$memory,
70
			0,
71
			0
72
		);
73
74
		$this->queries = [];
75
		$this->meta    = [];
76
		$this->config  = [];
77
78
	}
79
80
	public function start( $timer, $reset = false, $time = null ) {
81
82
		// not directly accessible
83
		if( !$timer ) return;
84
85
		if( !isset($this->timers[$timer]) || $reset ) {
86
			$this->timers[$timer] = new GenericTimer();
87
		}
88
89
		$this->timers[$timer]->start($time);
90
91
		return $this;
92
93
	}
94
95
	public function stop( $timer = null ) {
96
97
		if( !$timer ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $timer of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
98
			// stop user-defined timers
99
			foreach( $this->timers as $name => $timer ) {
100
				if( $name )
101
					$timer->stop();
102
			}
103
			// stop the internal timer last and mark the elapsed time
104
			$this->timers['']->stop();
105
			$this->mark('end');
106
		}
107
		elseif( isset($this->timers[$timer]) )  {
108
			$this->timers[$timer]->stop();
109
		}
110
111
		return $this;
112
113
	}
114
115
	public function isRunning( $timer = '' ) {
116
		return isset($this->timers[$timer]) ? $this->timers[$timer]->isRunning() : false;
117
	}
118
119
	public function getElapsed( $timer = '' ) {
120
		return isset($this->timers[$timer]) ? $this->timers[$timer]->getElapsed() : 0.0;
121
	}
122
123
	public function getTotalElapsed( $timer = '' ) {
124
		return isset($this->timers[$timer]) ? $this->timers[$timer]->getTotalElapsed() : 0.0;
125
	}
126
127
	public function mark( $name = '' ) {
128
129
		$prev    = end($this->marks);
130
		$elapsed = $this->timers['']->getTotalElapsed();
131
		$memory  = memory_get_usage();
132
133
		$this->marks[$name] = new Mark(
134
			$name,
135
			$elapsed,
136
			$memory,
137
			$elapsed - $prev->elapsed,
138
			$memory - $prev->memory
139
		);
140
141
		return $this->marks[$name];
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->marks[$name]; (yolk\profiler\Mark) is incompatible with the return type declared by the interface yolk\contracts\profiler\Profiler::mark of type yolk\contracts\profiler\Mark.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
142
143
	}
144
145
	public function query( $query, $parameters, $duration ) {
146
		$this->queries[] = [
147
			'query'    => $query,
148
			'params'   => $parameters,
149
			'duration' => round($duration, 6),
150
		];
151
		return $this;
152
	}
153
154
	public function meta( $key, $value = null ) {
155
		if( $value === null )
156
			unset($this->meta[$key]);
157
		else
158
			$this->meta[$key] = $value;
159
		return $this;
160
	}
161
162
	public function config( Arrayable $config ) {
163
		$this->config = $config->toArray();
164
		return $this;
165
	}
166
167
	public function getQueries() {
168
		return $this->queries;
169
	}
170
171
	public function getData() {
172
173
		$report = [
174
			'duration' => round($this->timers['']->getTotalElapsed(), 6),
175
			'memory'   => memory_get_peak_usage(),
176
			'timers'   => [],
177
			'marks'    => [],
178
			'queries'  => $this->queries,
179
			'meta'     => $this->meta,
180
			'config'   => $this->config,
181
			'includes' => get_included_files()
182
		];
183
184
		foreach( $this->timers as $name => $timer ) {
185
			$report['timers'][$name] = round($timer->getTotalElapsed(), 6);
186
		}
187
		unset($report['timers']['']);
188
		ksort($report['timers']);
189
190
		foreach( $this->marks as $name => $mark ) {
191
			$report['marks'][$name] = $mark->toArray();
192
			unset($report['marks'][$name]['name']);
193
		}
194
195
		return $report;
196
197
	}
198
199
	public function getHTML() {
200
		ob_start();
201
		$report = $this->getData();
202
		include __DIR__. '/debug-bar/main.php';
203
		return ob_get_clean();
204
	}
205
206
	public function dump( $dumper = '\\yolk\\debug\\TextDumper', $depth = 1 ) {
207
		if( $depth > 1 ) {
208
			return sprintf(
209
				"%s {\n%selapsed: %s ms\n%smemory : %s MB\n%squeries: %d\n%smarks  : %d\n%s}",
210
				get_class($this),
211
				str_repeat("\t", $depth),
212
				number_format($this->getElapsed() * 1000),
213
				str_repeat("\t", $depth),
214
				number_format(memory_get_peak_usage() / 1024 / 1024, 3),
215
				str_repeat("\t", $depth),
216
				count($this->queries),
217
				str_repeat("\t", $depth),
218
				count($this->marks),
219
				str_repeat("\t", $depth - 1)
220
			);
221
		}
222
	}
223
224
}
225
226
// EOF