Passed
Push — develop ( 2969a7...df24bb )
by Felipe
05:41 queued 11s
created

HelperTrait   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 208
Duplicated Lines 0 %

Importance

Changes 6
Bugs 1 Features 0
Metric Value
eloc 67
c 6
b 1
f 0
dl 0
loc 208
rs 9.84
wmc 32

12 Methods

Rating   Name   Duplication   Size   Complexity  
A halt() 0 6 1
A addFlash() 0 7 2
A formatSizeUnits() 0 17 6
A prtrace() 0 3 1
A recordSetToArray() 0 13 4
A br2ln() 0 3 1
A dump() 0 3 1
A setIfIsset() 0 14 3
A getBackTrace() 0 22 3
A dumpAndDie() 0 3 1
A staticTrace() 0 20 6
A coalesceArr() 0 7 3
1
<?php
2
3
/**
4
 * PHPPgAdmin v6.0.0-RC6
5
 */
6
7
namespace PHPPgAdmin\Traits;
8
9
/**
10
 * @file
11
 * A trait with helpers methods to debug, halt the app and format text to html
12
 */
13
14
/**
15
 * A trait with helpers methods to debug, halt the app and format text to html.
16
 */
17
trait HelperTrait
18
{
19
    /**
20
     * Halts the execution of the program. It's like calling exit() but using builtin Slim Exceptions.
21
     *
22
     * @param string $msg The message to show to the user
23
     *
24
     * @throws \Slim\Exception\SlimException (description)
25
     */
26
    public function halt($msg = 'An error has happened')
27
    {
28
        $body = $this->container->responseobj->getBody();
29
        $body->write($msg);
30
31
        throw new \Slim\Exception\SlimException($this->container->requestobj, $this->container->responseobj);
32
    }
33
34
    /**
35
     * Adds a flash message to the session that will be displayed on the next request.
36
     *
37
     * @param mixed  $content msg content (can be object, array, etc)
38
     * @param string $key     The key to associate with the message. Defaults to the stack
39
     *                        trace of the closure or method that called addFlassh
40
     */
41
    public function addFlash($content, $key = '')
42
    {
43
        if ($key === '') {
44
            $key = self::getBackTrace();
45
        }
46
        // $this->dump(__METHOD__ . ': addMessage ' . $key . '  ' . json_encode($content));
47
        $this->container->flash->addMessage($key, $content);
48
    }
49
50
    public static function getBackTrace($offset = 0)
51
    {
52
        $i0        = $offset;
53
        $i1        = $offset + 1;
54
        $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $offset + 3);
55
56
        $btarray0 = ([
57
            'class'    => $backtrace[$i1]['class'] === 'Closure' ?
58
            $backtrace[$i0]['file'] :
59
            $backtrace[$i1]['class'],
60
61
            'type'     => $backtrace[$i1]['type'],
62
63
            'function' => $backtrace[$i1]['function'] === '{closure}'
64
            ? $backtrace[$i0]['function'] :
65
            $backtrace[$i1]['function'],
66
67
            'spacer4'  => ' ',
68
            'line'     => $backtrace[$i0]['line'],
69
        ]);
70
71
        return $btarray0;
72
        //dump($backtrace);
73
    }
74
75
    /**
76
     * Converts an ADORecordSet to an array.
77
     *
78
     * @param \PHPPgAdmin\ADORecordSet $set   The set
79
     * @param string                   $field optionally the field to query for
80
     *
81
     * @return array the parsed array
82
     */
83
    public static function recordSetToArray($set, $field = '')
84
    {
85
        $result = [];
86
87
        if ($set->recordCount() <= 0) {
88
            return $result;
89
        }
90
        while (!$set->EOF) {
91
            $result[] = $field ? $set->fields[$field] : $set;
92
            $set->moveNext();
93
        }
94
95
        return $result;
96
    }
97
98
    /**
99
     * Checks if a variable is defined, in which case assign its value to $var1
100
     * If it isn't and $set is true, assign the default value. Otherwise don't
101
     * assign anything to $var1.
102
     *
103
     * @param mixed $var1    The variable to manipulate if $set if true
104
     * @param mixed $var2    The value to assign to $var1 if it's defined
105
     * @param mixed $default The default value to set, it $set is true
106
     * @param bool  $set     True to set the default value if $var2 isn't defined
107
     *
108
     * @return mixed the value of $var2 is $var2 is set, or $default otherwise
109
     */
110
    public function setIfIsset(&$var1, $var2, $default = null, $set = true)
111
    {
112
        if (isset($var2)) {
113
            $var1 = $var2;
114
115
            return $var1;
116
        }
117
        if ($set === true) {
118
            $var1 = $default;
119
120
            return $var1;
121
        }
122
123
        return $default;
124
    }
125
126
    /**
127
     * Checks if the $key of an $array is set. If it isn't, optionally set it to
128
     * the default parameter.
129
     *
130
     * @param array      $array   The array to check
131
     * @param int|string $key     The key to check
132
     * @param mixed      $default The default value to set, it $set is true
133
     * @param bool       $set     True to set the default value if $key isn't
134
     *                            set
135
     *
136
     * @return array the original array
137
     */
138
    public function coalesceArr(&$array, $key, $default = null, $set = true)
139
    {
140
        if (!isset($array[$key]) && $set === true) {
141
            $array[$key] = $default;
142
        }
143
144
        return $array;
145
    }
146
147
    public static function formatSizeUnits($bytes, $lang)
148
    {
149
        if ($bytes == -1) {
150
            $bytes = $lang['strnoaccess'];
151
        } elseif ($bytes >= 1099511627776) {
152
            $bytes = sprintf('%s %s', number_format($bytes / 1099511627776, 0), $lang['strtb']);
153
        } elseif ($bytes >= 1073741824) {
154
            $bytes = sprintf('%s %s', number_format($bytes / 1073741824, 0), $lang['strgb']);
155
        } elseif ($bytes >= 1048576) {
156
            $bytes = sprintf('%s %s', number_format($bytes / 1048576, 0), $lang['strmb']);
157
        } elseif ($bytes >= 1024) {
158
            $bytes = sprintf('%s %s', number_format($bytes / 1024, 0), $lang['strkb']);
159
        } else {
160
            $bytes = sprintf('%s %s', $bytes, $lang['strbytes']);
161
        }
162
163
        return $bytes;
164
    }
165
166
    /**
167
     * Returns a string with html <br> variant replaced with a new line.
168
     *
169
     * @param string $msg message to parse (<br> separated)
170
     *
171
     * @return string parsed message (linebreak separated)
172
     */
173
    public static function br2ln($msg)
174
    {
175
        return str_replace(['<br>', '<br/>', '<br />'], PHP_EOL, $msg);
176
    }
177
178
    /**
179
     * Receives N parameters and sends them to the console adding where was it called from.
180
     */
181
    public function prtrace(...$args)
182
    {
183
        return self::staticTrace($args);
184
    }
185
186
    public function dump(...$args)
187
    {
188
        return self::staticTrace($args);
189
    }
190
191
    /**
192
     * Receives N parameters and sends them to the console adding where was it
193
     * called from.
194
     *
195
     * @param mixed $variablesToDump
196
     * @param mixed $exitAfterwards
0 ignored issues
show
Coding Style introduced by
Doc comment for parameter $exitAfterwards does not match actual variable name $whoCalledMe
Loading history...
197
     */
198
    private static function staticTrace(
199
        $variablesToDump = [],
200
        string $whoCalledMe = '',
201
        $exitAfterwards = false
202
    ) {
203
        if (!$variablesToDump) {
204
            $variablesToDump = func_get_args();
205
        }
206
        if ($whoCalledMe === '') {
207
            $whoCalledMe = str_replace(BASE_PATH, '', implode('', self::getBackTrace(2)));
208
        }
209
        if ($exitAfterwards && function_exists('dd')) {
210
            dd([
211
                'args' => $variablesToDump,
212
                'from' => $whoCalledMe,
213
            ]);
214
        } elseif (function_exists('dump')) {
215
            dump([
0 ignored issues
show
Bug introduced by
The call to dump() has too few arguments starting with str. ( Ignorable by Annotation )

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

215
            /** @scrutinizer ignore-call */ 
216
            dump([

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
216
                'args' => $variablesToDump,
217
                'from' => $whoCalledMe,
218
            ]);
219
        }
220
    }
221
222
    public function dumpAndDie(...$args)
223
    {
224
        return self::staticTrace($args);
225
    }
226
}
227