Lib::quoteArg()   A
last analyzed

Complexity

Conditions 5
Paths 10

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 9
nc 10
nop 1
dl 0
loc 16
ccs 10
cts 10
cp 1
crap 5
rs 9.6111
c 0
b 0
f 0
1
<?php
2
3
/* this file is part of pipelines */
4
5
namespace Ktomk\Pipelines;
6
7
class Lib
8
{
9 1
    public static function id($v)
10
    {
11 1
        return $v;
12
    }
13
14
    /**
15
     * @param mixed $v
16
     * @param mixed $d
17
     *
18
     * @return mixed
19
     */
20 2
    public static function r(&$v, $d)
21
    {
22 2
        if (isset($v)) {
23 1
            return $v;
24
        }
25
26 1
        return $d;
27
    }
28
29
    /**
30
     * @param mixed $v variable reference
31
     * @param mixed $d [optional]  default value (null)
32
     *
33
     * @return void
34
     */
35 2
    public static function v(&$v, $d = null)
36
    {
37 2
        if (!isset($v)) {
38 1
            $v = $d;
39
        }
40
    }
41
42
    /**
43
     * @return string UUID version 4
44
     */
45 1
    public static function generateUuid()
46
    {
47 1
        return sprintf(
48
            '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
49
50
            // 32 bits for "time_low"
51 1
            mt_rand(0, 0xffff),
52 1
            mt_rand(0, 0xffff),
53
54
            // 16 bits for "time_mid"
55 1
            mt_rand(0, 0xffff),
56
57
            // 16 bits for "time_hi_and_version",
58
            // four most significant bits holds version number 4
59 1
            mt_rand(0, 0x0fff) | 0x4000,
60
61
            // 16 bits, 8 bits for "clk_seq_hi_res",
62
            // 8 bits for "clk_seq_low",
63
            // two most significant bits holds zero and one for variant DCE1.1
64 1
            mt_rand(0, 0x3fff) | 0x8000,
65
66
            // 48 bits for "node"
67 1
            mt_rand(0, 0xffff),
68 1
            mt_rand(0, 0xffff),
69 1
            mt_rand(0, 0xffff)
70
        );
71
    }
72
73
    /**
74
     * @param string $command
75
     * @param array|string[] $arguments
76
     *
77
     * @return string
78
     */
79 2
    public static function cmd($command, array $arguments)
80
    {
81 2
        $buffer = $command;
82
83 2
        $arguments = self::mergeArray($arguments);
84
85 2
        foreach ($arguments as $argument) {
86 2
            $buffer .= ' ' . self::quoteArg($argument);
87
        }
88
89 2
        return $buffer;
90
    }
91
92
    /**
93
     * quote an argument to preserve its value verbatim when used as
94
     * a utility argument in shell
95
     *
96
     * @param string $argument
97
     *
98
     * @return string
99
     */
100 9
    public static function quoteArg($argument)
101
    {
102 9
        $parts = explode("'", $argument);
103
104 9
        $buffer = '';
105 9
        foreach ($parts as $index => $part) {
106 9
            $index && $buffer .= "\\'";
107 9
            $safe = preg_match('~^[a-zA-Z0-9,._+@%/-]*$~D', $part);
108 9
            $buffer .= $safe ? $part : "'{$part}'";
109
        }
110
111 9
        if ('' === $buffer) {
112 1
            $buffer = "''";
113
        }
114
115 9
        return $buffer;
116
    }
117
118
    /**
119
     * Turn multi-line string into an array of lines.
120
     *
121
     * Handles (no) newline at the end of buffer
122
     *
123
     * @param string $buffer
124
     *
125
     * @return array|string[]
126
     */
127 1
    public static function lines($buffer)
128
    {
129 1
        $lines = explode("\n", $buffer);
130 1
        $c = count($lines);
131 1
        if ($c && '' === $lines[$c - 1]) {
132 1
            array_pop($lines);
133
        }
134
135 1
        return $lines;
136
    }
137
138
    /**
139
     * merge n array parameters
140
     *
141
     * all parameters should be of type array. if a parameter ist not
142
     * an array it is promoted to one as the following:
143
     *
144
     *   - null => []             # null is an empty array
145
     *   - skalar => [skalar]     # skalar is an array with itself as single value
146
     *   - resource => [resource] # same as skalar
147
     *   - object => [object]     # same as skalar
148
     *
149
     * to produce a merged array of all these arrays.
150
     *
151
     * examples:
152
     *
153
     *     (null, null) => []
154
     *     ([null], [null]) => [null, null]
155
     *     (1, 2, 3) => [1, 2, 3]
156
     *     ([1, 2], 3) => [1, 2, 3]
157
     *     ([1, 2], ['a', 'b']) => [1, 2, 'a', 'b']
158
     *
159
     * @return array
160
     */
161 2
    public static function merge()
162
    {
163 2
        $arrays = func_get_args();
164
165 2
        if (empty($arrays)) {
166 1
            return $arrays;
167
        }
168
169 1
        return self::mergeArray($arrays);
170
    }
171
172
    /**
173
     * merge n array parameters
174
     *
175
     * {@see Lib::merge} with a single parameter
176
     *
177
     * @return array of merged parameters
178
     */
179 4
    public static function mergeArray(array $parameters)
180
    {
181 4
        if (empty($parameters)) {
182 1
            return $parameters;
183
        }
184
185 3
        foreach ($parameters as $key => $value) {
186 3
            if (!is_array($value)) {
187 3
                $parameters[$key] = null === $value ? array() : array($value);
188
            }
189
        }
190
191 3
        return call_user_func_array('array_merge', $parameters);
192
    }
193
194
    /**
195
     * @param callable $callable
196
     * @param iterable $iterable
197
     *
198
     * @return int count of calls
199
     */
200 1
    public static function iterEach($callable, $iterable)
201
    {
202 1
        $count = 0;
203 1
        foreach ($iterable as $key => $value) {
204 1
            $count++;
205 1
            call_user_func($callable, $value, $key, $iterable);
206
        }
207
208 1
        return $count;
209
    }
210
211
    /**
212
     * @param callable $callable
213
     * @param iterable $iterable
214
     *
215
     * @return array
216
     */
217 1
    public static function iterMap($callable, $iterable)
218
    {
219 1
        $map = array();
220 1
        foreach ($iterable as $key => $value) {
221 1
            $map[$key] = call_user_func($callable, $value);
222
        }
223
224 1
        return $map;
225
    }
226
227
    /**
228
     * Chunk an array of strings based on maximum string length per chunk
229
     *
230
     * @param array|string[] $array
231
     * @param int $maxLength
232
     * @param int $overHeadPerEntry
233
     *
234
     * @return array|array[]
235
     */
236 2
    public static function arrayChunkByStringLength(array $array, $maxLength, $overHeadPerEntry = 0)
237
    {
238 2
        $chunks = array();
239 2
        $chunkStringLength = 0;
240 2
        $chunk = array();
241
242 2
        foreach ($array as $key => $value) {
243 2
            $entryLen = strlen($value) + $overHeadPerEntry;
244 2
            if ($chunkStringLength + $entryLen > $maxLength) {
245 2
                if (empty($chunk)) {
246 1
                    throw new \InvalidArgumentException(sprintf(
247
                        'maximum length of %d is too little to chunk the array at %s %s (%d chunk(s) so far)',
248
                        $maxLength,
249 1
                        is_string($key) ? 'key' : 'index',
250 1
                        is_string($key) ? var_export($key, true) : (int)$key,
251 1
                        count($chunks)
252
                    ));
253
                }
254 1
                $chunks[] = $chunk;
255 1
                $chunk = array();
256 1
                $chunkStringLength = 0;
257
            }
258 1
            $chunk[] = $value;
259 1
            $chunkStringLength += $entryLen;
260
        }
261
262 1
        if (!empty($chunk)) {
263 1
            $chunks[] = $chunk;
264
        }
265
266 1
        return $chunks;
267
    }
268
269
    /**
270
     * Get shell environment variables only from $_SERVER in PHP CLI
271
     *
272
     * Filter an array like $_SERVER in PHP CLI shell for environment
273
     * variables only.
274
     *
275
     * @param array $server
276
     *
277
     * @return array|string[]
278
     */
279 1
    public static function env(array $server)
280
    {
281 1
        return array_filter(
282
            // Pipelines must not support environment variable names with '=' in them
283 1
            array_flip(preg_grep('~=~', array_keys($server)))
284
            // What PHP might have added
285
            + array(
286 1
                'PHP_SELF' => null,
287
                'SCRIPT_NAME' => null,
288
                'SCRIPT_FILENAME' => null,
289
                'PATH_TRANSLATED' => null,
290
                'DOCUMENT_ROOT' => null,
291
                'REQUEST_TIME_FLOAT' => null,
292
                'REQUEST_TIME' => null,
293
                'argv' => null,
294
                'argc' => null,
295
            )
296
            + $server,
297
            'is_string'
298
        );
299
    }
300
301
    /**
302
     * fallback for the php 5.3 version which does not have PHP_BINARY.
303
     *
304
     * fallback for the php 5.4-8.0 versions which do have an empty
305
     * PHP_BINARY when executed w/o absolute path in argv[0]
306
     *
307
     * @return string
308
     */
309 1
    public static function phpBinary()
310
    {
311 1
        return defined('PHP_BINARY') && '' !== constant('PHP_BINARY') ? constant('PHP_BINARY') : PHP_BINDIR . '/php';
312
    }
313
314
    /**
315
     * Empty "coalesce" function
316
     *
317
     * @return mixed
318
     */
319 1
    public static function emptyCoalesce()
320
    {
321 1
        foreach (func_get_args() as $arg) {
322 1
            if (empty($arg)) {
323 1
                continue;
324
            }
325
326 1
            return $arg;
327
        }
328
329 1
        return null;
330
    }
331
}
332