Passed
Pull Request — develop (#262)
by Felipe
04:12
created

HelperTrait::getSubfolder()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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

250
            /** @scrutinizer ignore-call */ 
251
            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...
251
                'args' => $variablesToDump,
252
                'from' => $whoCalledMe,
253
            ]);
254
        }
255
    }
256
}
257