Completed
Push — master ( 77e54d...89ae78 )
by Agel_Nash
03:12
created

debug.functions.php ➔ format_exception()   B

Complexity

Conditions 6
Paths 24

Size

Total Lines 34
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 21
nc 24
nop 4
dl 0
loc 34
rs 8.439
c 0
b 0
f 0
1
<?php
2
if (!function_exists('hide_errors')) {
3
	/**
4
	 * Не отображать и не логировать ошибки скриптов
5
	 *
6
	 * @return void
7
	 */
8
	function hide_errors()
9
	{
10
		error_reporting(0);
11
		ini_set('display_errors', false);
12
	}
13
}
14
15
if (!function_exists('show_errors')) {
16
	/**
17
	 * Показать все ошибки скриптов
18
	 *
19
	 * @return void
20
	 */
21
	function show_errors()
22
	{
23
		error_reporting(E_ALL);
24
		ini_set('display_errors', true);
25
	}
26
}
27
28
if (!function_exists('dd')) {
29
	/**
30
	 * Удалить буфер вывода, сделать дамп параметров функции и прервать выполнение скрипта
31
	 *
32
	 * @param  mixed
33
	 * @return void
34
	 */
35
	function dd()
36
	{
37
		ob_clean();
38
		array_map(function($x) {
39
			var_dump($x);
40
		}, func_get_args());
41
		die;
42
	}
43
}
44
45
if (!function_exists('array_code')) {
46
	/**
47
	 * Печать массива в том виде, в котором его понимает php
48
	 *
49
	 * @param array $arr Массив с выходными данными
50
	 * @param int $level До какого уровня вложенности строить массив
51
	 * @return string
52
	 */
53
	function array_code($arr, $level = 1)
54
	{
55
		$php = $tabs = $breaks = '';
56
		if (is_array($arr)) {
57
			for ($n = 0; $n < $level; $n++) {
58
				$tabs .= "\t";
59
				if ($n > 0) {
60
					$breaks .= "\t";
61
				}
62
			}
63
			$vals = array();
64
			foreach ($arr as $key => $val) {
65
				$vals[] = is_array($val) ? "'" . $key . "'=>" . array_code($val, $level + 1) : "'" . $key . "'=>'" . $val . "'";
66
			}
67
			$php = "array(\r" . $tabs . implode(",\r" . $tabs, $vals) . "\r" . $breaks . ")";
68
		}
69
70
		return $php;
71
	}
72
}
73
74
if (!function_exists('show_var')) {
75
	/**
76
	 * Показать содержимое переменной
77
	 * @param mixed $html
78
	 * @return string
79
	 */
80
	function show_var($html)
81
	{
82
		return html_wrap('pre', e(print_r($html, 1)));
83
	}
84
}
85
if (!function_exists('point_info')){
86
	/**
87
	 * Информация о ресурсах потребляемых на каком-то участке кода
88
	 * @param string $key Имя метки
89
	 * @param bool $store Необходимо ли сохранить информацию о метке в памяти
90
	 * @param bool $clear Нужно ли выполнить сброс меток
91
	 */
92
	function point_info($key, $store = false, $clear = false){
93
		static $marks = array();
94
		$out = array();
95
		
96
		if(is_scalar($key) && !empty($key)){
97
			if($store){
98
				$marks[$key] = array(
99
					'time' => microtime(true), 
100
					'memory' => memory_get_usage()
101
				);
102
				$out = array(
103
					'memory' => format_bytes($marks[$key]['memory']),
104
					'time' => format_microtime($marks[$key]['time'])
105
				);
106
			}else{
107
				$out = get_key($marks, $key, array(
108
					'time' => get_key($_SERVER, 'REQUEST_TIME_FLOAT', 0), 
109
					'memory'=> 0
110
				), 'is_array');
0 ignored issues
show
Documentation introduced by
'is_array' is of type string, but the function expects a object<Closure>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
111
				$out['time'] = format_microtime(microtime(true) - $out['time']);
112
				$out['memory'] = format_bytes(memory_get_usage() - $out['memory']);
113
			}
114
		}
115
	
116
		if ($clear) {
117
			$marks = array();
118
		}
119
		return $out;
120
	}
121
}
122
123
if (!function_exists('call_private_method')) {
124
	/**
125
	 * Возможность вызвать любой метод (даже приватный)
126
	 * call_private_method($myObject, 'myMethod', array('myValue1', 'myValue2'));
127
	 * 
128
	 * @see http://gostash.it/ru/stashes/236
129
	 * @param mixed $object Объект у которого требуется обратиться к методу
130
	 * @param string $method Вызываемый метод
131
	 * @param array $args Параметры метода
132
	 */
133
	function call_private_method($object, $method, $args)
134
	{
135
		$classReflection = new \ReflectionClass(get_class($object));
136
		$methodReflection = $classReflection->getMethod($method);
137
		$methodReflection->setAccessible(true);
138
		$result = $methodReflection->invokeArgs($object, $args);
139
		$methodReflection->setAccessible(false);
140
		return $result;
141
	}
142
}
143
144
if (! function_exists('format_exception')) {
145
	/**
146
	 * Форматировавние исключений для логирования или удобоваримого отображения
147
	 *
148
	 * @param Exception $exception обрабатываемое исключение
149
	 * @param bool $trace включить ли трассировку в отчет
150
	 * @param null|string $file Файл в котором вызвана обработка исключения
151
								Удобнее всего передавать константу __FILE__ в качестве аргумента
152
	 * @param null|int $line Строка в файле где вызвана обработка исключения
153
								Удобнее всего передавать константу __LINE__ в качестве аргумента
154
	 * @return string
155
	 */
156
	function format_exception(Exception $exception, $trace = false, $file = null, $line = null)
157
	{
158
		$msg = get_class($exception);
159
160
		$code = $exception->getCode();
161
		if (! empty($code)) {
162
			$msg .= ':' . $exception->getCode();
163
		}
164
		$msg .= PHP_EOL;
165
166
		$tmp = $exception->getMessage();
167
		if (! empty($tmp)) {
168
			$msg .= $exception->getMessage();
169
			$msg .= PHP_EOL;
170
		}
171
172
		if ($trace === true) {
173
			$msg .= PHP_EOL;
174
			$msg .= $exception->getTraceAsString();
175
			$msg .= PHP_EOL . PHP_EOL;
176
		}
177
178
		if ($file !== null) {
179
			$msg .= $file;
180
			if ($line !== null) {
181
				$msg .= ':' . $line;
182
			}
183
			$msg .= PHP_EOL;
184
		}
185
186
		$msg .= $exception->getFile() . ':' . $exception->getLine();
187
188
		return $msg;
189
	}
190
}