hide_errors()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 2
b 0
f 0
nc 1
nop 0
dl 0
loc 4
ccs 0
cts 2
cp 0
crap 2
rs 10
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);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type string expected by parameter $newvalue of ini_set(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

11
        ini_set('display_errors', /** @scrutinizer ignore-type */ false);
Loading history...
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);
0 ignored issues
show
Bug introduced by
true of type true is incompatible with the type string expected by parameter $newvalue of ini_set(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

24
        ini_set('display_errors', /** @scrutinizer ignore-type */ true);
Loading history...
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);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($x) looks like debug code. Are you sure you do not want to remove it?
Loading history...
40
        }, func_get_args());
41
        die;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
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)) {
0 ignored issues
show
introduced by
The condition is_array($arr) is always true.
Loading history...
57
            for ($n = 0; $n < $level; $n++) {
58
                $tabs .= "\t";
59
                if ($n > 0) {
60
                    $breaks .= "\t";
61
                }
62
            }
63
            $vals = [];
64
            foreach ($arr as $key => $val) {
65
                $vals[] = is_array($val) ?
66
                    "'" . $key . "'=>" . array_code($val, $level + 1) :
67
                    "'" . $key . "'=>'" . $val . "'";
68
            }
69
            $php = "array(\r" . $tabs . implode(",\r" . $tabs, $vals) . "\r" . $breaks . ")";
70
        }
71
72
        return $php;
73
    }
74
}
75
76
if (! function_exists('show_var')) {
77
    /**
78
     * Показать содержимое переменной
79
     * @param mixed $html
80
     * @return string
81
     */
82
    function show_var($html)
83
    {
84
        return html_wrap('pre', e(print_r($html, 1)));
85
    }
86
}
87
if (! function_exists('point_info')) {
88
    /**
89
     * Информация о ресурсах потребляемых на каком-то участке кода
90
     * @param string $key Имя метки
91
     * @param bool $store Необходимо ли сохранить информацию о метке в памяти
92
     * @param bool $clear Нужно ли выполнить сброс меток
93
     */
94
    function point_info($key, $store = false, $clear = false)
95
    {
96
        static $marks = [];
97
        $out = [];
98
99
        if (is_scalar($key) && ! empty($key)) {
100
            if ($store) {
101
                $marks[$key] = [
102
                    'time'   => microtime(true),
103
                    'memory' => memory_get_usage()
104
                ];
105
                $out = [
106
                    'memory' => format_bytes($marks[$key]['memory']),
107
                    'time'   => format_microtime($marks[$key]['time'])
108
                ];
109
            } else {
110
                $out = get_key($marks, $key, [
111
                    'time'   => get_key($_SERVER, 'REQUEST_TIME_FLOAT', 0),
112
                    'memory' => 0
113
                ], 'is_array');
0 ignored issues
show
Bug introduced by
'is_array' of type string is incompatible with the type Closure expected by parameter $validate of get_key(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

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