Passed
Push — master ( ebceb8...305567 )
by Stephen
01:13
created

randomPassword()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 3
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Sanitize a file name to remove illegal chars.
5
 *
6
 * @param string $raw
7
 * @return string
8
 */
9
function sanitizeFileName(string $raw): string
10
{
11
    return preg_replace('/[^A-Za-z0-9_\-]/', '_', $raw);
12
}
13
14
/**
15
 * Truncate a string to be no longer than $chars.
16
 *
17
 * @param string $string
18
 * @param int $chars
19
 * @param string $suffix
20
 * @return string
21
 */
22
function truncateString(string $string, int $chars = 100, string $suffix = '...'): string
23
{
24
    return (strlen($string) <= $chars) ? $string : substr($string, 0, $chars).$suffix;
25
}
26
27
/**
28
 * Covert a camel cased string into a $char separated string.
29
 *
30
 * @param string $string
31
 * @param string $char
32
 * @return string
33
 */
34
function camelCaseConverter(string $string, $char = '-'): string
35
{
36
    return strtolower(preg_replace('/(?<!^)[A-Z]/', $char.'$0', $string));
37
}
38
39
/**
40
 * Implode values that are not null.
41
 *
42
 * @param $glue
43
 * @param array $pieces
44
 * @return string|null
45
 */
46
function implodeFiltered($glue, array $pieces)
47
{
48
    if (! empty($pieces) && count($pieces) > 0) {
49
        return implode($glue, array_filter($pieces, function ($attr) {
50
            return isset($attr);
51
        }));
52
    } else {
53
        return null;
54
    }
55
}
56
57
/**
58
 * Retrieve a website domain without prefixes.
59
 *
60
 * @param string $url
61
 * @return string
62
 */
63
function extractWebsiteDomain(string $url)
64
{
65
    return isset($url) ? str_replace('www.', '', parse_url($url)['host']) : '';
66
}
67
68
/**
69
 * Only retrieve an integer value if the $value is greater than zero.
70
 *
71
 * Uses $return as the $return value instead of $value if not null.
72
 * Return original $value or $return if it is greater than zero.
73
 * Return $substitute string if it is less.
74
 *
75
 * @param $value
76
 * @param string $substitute
77
 * @param mixed $return
78
 * @return mixed|string
79
 */
80
function zero_replace($value, $substitute = '-', $return = null)
81
{
82
    // Return $substitute if the $value is not greater than the 0
83
    return $value > 0 ? ($return ?? (int) $value) : $substitute;
84
}
85
86
/**
87
 * Remove illegal characters from a string to create an ID.
88
 *
89
 * @param $string
90
 * @return string
91
 */
92
function str2id($string)
93
{
94
    return strtolower(str_replace(' ', '-', str_replace('&', '-', $string)));
95
}
96
97
/**
98
 * Remove ' ', '-', '&' characters.
99
 *
100
 * @param $item
101
 * @return string
102
 */
103
function stripString($item)
104
{
105
    return strtolower(str_replace(',', '', str_replace(' ', '-', str_replace('&', '', $item))));
106
}
107
108
/**
109
 * Remove spaces and convert string to lowercase chars.
110
 *
111
 * @param $string
112
 * @return string|string[]
113
 */
114
function stringID($string)
115
{
116
    return str_replace(' ', '-', strtolower($string));
117
}
118
119
/**
120
 * Check if a needle string is in a haystack string.
121
 *
122
 * @param string $haystack
123
 * @param string $needle
124
 * @return bool
125
 */
126
function inString(string $haystack, string $needle): bool
127
{
128
    return strpos($haystack, $needle) !== false;
129
}
130
131
/**
132
 * Determine if the $string is a plain text list of values.
133
 *
134
 *  - if $string is a list, an array of values is returned
135
 *  - if $sting is a string, false is returned
136
 *
137
 * @param string $string
138
 * @param array|string[] $separators
139
 * @return bool|false|string[]
140
 */
141
function isListString(string $string, array $separators = [', ', ' '])
142
{
143
    foreach ($separators as $needle) {
144
        // If the $needle is found in the $string
145
        // we know the string is a plain text list
146
        // so an array of values is returned
147
        if (inString($string, $needle)) {
148
            return explode($needle, $string);
149
        }
150
    }
151
152
    // If none of the separators are found
153
    // we know the string is not a list
154
    return false;
155
}
156
157
/**
158
 * Explode a string using an array of delimiters instead of a single string.
159
 *
160
 * @param string $string
161
 * @param array|string[] $delimiters
162
 * @param string $replacer
163
 * @return array
164
 */
165
function explodeMany(string $string,
166
                     array $delimiters = [',', '&', '/', '-'],
167
                     string $replacer = '***'): array
168
{
169
    // Replace all of $delimiters chars with the
170
    // $replacer so that a single delimiter can
171
    // be used to explode the string
172
    $cleaned = str_replace($delimiters, $replacer, $string);
173
174
    // Use the replacer as the $delimiter
175
    // since it has replaced each of the
176
    // passed $delimiters
177
    $split = explode($replacer, $cleaned);
178
179
    // Utilize collection's if laravel/framework is installed
180
    if (function_exists('collect')) {
181
        // Collect the array of strings
182
        return collect($split)
183
184
            // Remove empty strings from the collection
185
            ->filter(function (string $item) {
186
                return strlen($item) > 0;
187
            })
188
189
            // Trim the remaining strings in the collection
190
            ->map(function (string $item) {
191
                return trim($item);
192
            })
193
194
            // Encode as array
195
            ->toArray();
196
    }
197
198
    // Use built in array functions
199
    else {
200
        // Remove empty strings from the collection
201
        $filtered = array_filter($split, function (string $item) {
202
            return strlen($item) > 0;
203
        });
204
205
        // Trim the remaining strings in the collection
206
        return  array_map(function (string $item) {
207
            return trim($item);
208
        }, $filtered);
209
    }
210
}
211
212
/**
213
 * Pretty implode an array by using a different glue for the last piece.
214
 *
215
 * Examples:
216
 *  - implodePretty([1, 2, 3]) --> '1, 2 & 3'
217
 *  - implodePretty([A, B, D]) --> 'A, B & D'
218
 *
219
 * @param array $pieces
220
 * @param string $glue
221
 * @param string $and
222
 * @return string
223
 */
224
function implodePretty(array $pieces, string $glue = ',', string $and = '&')
225
{
226
    // Pop off the last item so that it's
227
    // imploded with the $and char
228
    $last = array_pop($pieces);
229
230
    // Do nothing and return $last if there
231
    // are no remaining $pieces
232
    if (! count($pieces)) {
233
        return $last;
234
    }
235
236
    // Implode all bust the last $piece
237
    // using the $glue char
238
    $start = implode(whitespacePadBack(trim($glue)), $pieces);
239
240
    // Implode comma separated $start with
241
    // & separated $last
242
    return implode(whitespacePad(trim($and)), [$start, $last]);
243
}
244
245
/**
246
 * Add whitespace padding to a string.
247
 *
248
 * @param string $string
249
 * @param int $amount
250
 * @param string $pad
251
 * @param bool $front add whitespace to 'front' of the string
252
 * @param bool $back add whitespace to the 'back' of the string
253
 * @return string
254
 */
255
function whitespacePad(string $string,
256
                       int $amount = 1,
257
                       string $pad = ' ',
258
                       bool $front = true,
259
                       bool $back = true)
260
{
261
    // Multiple $pad chars by $amount
262
    $whitespace = str_repeat($pad, $amount);
263
264
    // Return string with padding
265
    return ($front ? $whitespace : '').$string.($back ? $whitespace : '');
266
}
267
268
/**
269
 * Add whitespace padding to only the 'back' of the string.
270
 *
271
 * @param string $string
272
 * @param int $amount
273
 * @param string $pad
274
 * @return string
275
 */
276
function whitespacePadBack(string $string, int $amount = 1, string $pad = ' ')
277
{
278
    return whitespacePad($string, $amount, $pad, false, true);
279
}
280
281
/**
282
 * Add whitespace padding to only the 'back' of the string.
283
 *
284
 * @param string $string
285
 * @param int $amount
286
 * @param string $pad
287
 * @return string
288
 */
289
function whitespacePadFront(string $string, int $amount = 1, string $pad = ' ')
290
{
291
    return whitespacePad($string, $amount, $pad, true, false);
292
}
293
294
/**
295
 * Generate a random password using uniqueid & md5 functions.
296
 *
297
 * @param int $length
298
 * @param string $prefix
299
 * @param string $hashFunction
300
 * @return string
301
 */
302
function randomPassword(int $length = 8, string $prefix = '', string $hashFunction = 'md5'): string
303
{
304
    return $prefix.truncateString($hashFunction(uniqid()), $length, '');
305
}
306