Completed
Push — master ( 9802ab...25d319 )
by Lorenzo
03:18
created

string.php ➔ e()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 4
rs 10
1
<?php
2
3
/**
4
 * Generate random string (password) from a different charset based on $secLevel.
5
 * $secLevel=0 [a-z] charset.
6
 * $secLevel=1 [a-z0-9] charset.
7
 * $secLevel=2 [A-Za-z0-9] charset.
8
 * $secLevel=3 [A-Za-z0-9-_$!+&%?=*#@] charset.
9
 * @param int $length
10
 * @param int $secLevel
11
 * @return string
12
 */
13
function generateRandomPassword(int $length = 10, int $secLevel = 2) : string
14
{
15
    $charset = 'abcdefghijklmnopqrstuvwxyz';
16
    if ($secLevel == 1) {
17
        $charset = 'abcdefghijklmnopqrstuvwxyz1234567890';
18
    } elseif ($secLevel == 2) {
19
        $charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
20
    } elseif ($secLevel >= 3) {
21
        $charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890-_$!+&%?=*#@';
22
    }
23
24
    return generateRandomString($length, '', $charset);
25
}
26
27
/**
28
 * Generate random string from [0-9A-Za-z] charset.
29
 * You may extend charset by passing $extChars (i.e. add these chars to existing).
30
 * Ex.: $extChars='-_$!' implies that the final charset is [0-9A-Za-z-_$!]
31
 * If $newChars is set, the default charset are replaced by this and $extChars was ignored.
32
 * Ex.: $newChars='0123456789' implies that the final charset is [0123456789]
33
 * @param int $length
34
 * @param string $extChars
35
 * @param string $newChars
36
 * @return string
37
 */
38
function generateRandomString(int $length = 10, string $extChars = '', string $newChars = '') : string
39
{
40
    if ($length < 1) {
41
        $length = 1;
42
    }
43
44
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
45
    if ($newChars !== null && $newChars != '') {
46
        $characters = $newChars;
47
    } elseif ($extChars !== null && $extChars != '') {
48
        $characters .= $extChars;
49
    }
50
51
    $charactersLength = strlen($characters);
52
    $randomString = '';
53
54
    for ($i = 0; $i < $length; $i++) {
55
        $randomString .= $characters[random_int(0, $charactersLength - 1)];
56
    }
57
58
    return $randomString;
59
}
60
61
if (!function_exists('gravatar')) {
62
    /**
63
     * Get a Gravatar URL from email.
64
     *
65
     * @param string $email The email address
66
     * @param int $size in pixels, defaults to 80px [ 1 - 2048 ]
67
     * @param string $default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
68
     * @param string $rating (inclusive) [ g | pg | r | x ]
69
     * @return string
70
     * @source http://gravatar.com/site/implement/images/php/
71
     */
72
    function gravatar($email, $size = 80, $default = 'mm', $rating = 'g')
73
    {
74
        $url = 'http://www.gravatar.com/avatar/';
75
        $url .= md5(strtolower(trim($email)));
76
        $url .= "?s=$size&d=$default&r=$rating";
77
        return $url;
78
    }
79
}
80
81
/**
82
 * *****************************************************
83
 * LARAVEL STRING HELPERS
84
 * With some adjustments
85
 * *****************************************************
86
 */
87
88
if (!function_exists('preg_replace_sub')) {
89
    /**
90
     * Replace a given pattern with each value in the array in sequentially.
91
     *
92
     * @param  string $pattern
93
     * @param  array $replacements
94
     * @param  string $subject
95
     * @return string
96
     */
97
    function preg_replace_sub($pattern, &$replacements, $subject)
98
    {
99
        return preg_replace_callback($pattern, function () use (&$replacements) {
100
            return array_shift($replacements);
101
        }, $subject);
102
    }
103
}
104
105
if (!function_exists('snake_case')) {
106
    /**
107
     * Convert a string to snake case.
108
     *
109
     * @param  string $value
110
     * @param  string $delimiter
111
     * @return string
112
     */
113
    function snake_case($value, $delimiter = '_')
114
    {
115
        $snakeCache = [];
116
        $key = $value . $delimiter;
117
        if (isset($snakeCache[$key])) {
118
            return $snakeCache[$key];
119
        }
120
        if (!ctype_lower($value)) {
121
            $value = strtolower(preg_replace('/(.)(?=[A-Z])/', '$1' . $delimiter, $value));
122
        }
123
        return $snakeCache[$key] = $value;
124
    }
125
}
126
127
if (!function_exists('str_random')) {
128
    /**
129
     * Generate a more truly "random" alpha-numeric string with openssl.
130
     * If openssl_random_pseudo_bytes not exists, use simple legacy function
131
     *
132
     * @param  int $length
133
     * @return string
134
     *
135
     * @throws \RuntimeException
136
     */
137
    function str_random(int $length = 16)
138
    {
139
        if ($length < 0) {
140
            $length = 16;
141
        }
142
143
        if (!function_exists('openssl_random_pseudo_bytes')) {
144
            return generateRandomString($length);
145
        }
146
        $bytes = openssl_random_pseudo_bytes($length * 2);
147
        if ($bytes === false) {
148
            throw new RuntimeException('Unable to generate random string.');
149
        }
150
        return substr(str_replace(array('/', '+', '='), '', base64_encode($bytes)), 0, $length);
151
    }
152
}
153
154
if (!function_exists('ends_with')) {
155
    /**
156
     * Determine if a given string ends with a given substring.
157
     *
158
     * @param  string $haystack
159
     * @param  string|array $needles
160
     * @return bool
161
     */
162
    function ends_with($haystack, $needles)
163
    {
164
        if (isNullOrEmpty($haystack) || isNullOrEmpty($needles)) {
165
            return false;
166
        }
167
168
        foreach ((array)$needles as $needle) {
169
            if ((string)$needle === substr($haystack, -strlen($needle))) {
170
                return true;
171
            }
172
        }
173
        return false;
174
    }
175
}
176
177
if (!function_exists('starts_with')) {
178
    /**
179
     * Determine if a given string starts with a given substring.
180
     *
181
     * @param  string $haystack
182
     * @param  string|array $needles
183
     * @return bool
184
     */
185
    function starts_with($haystack, $needles)
186
    {
187
        if (isNullOrEmpty($haystack) || isNullOrEmpty($needles)) {
188
            return false;
189
        }
190
191
        foreach ((array)$needles as $needle) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
192
            if ($needle != '' && strpos($haystack, $needle) === 0) {
193
                return true;
194
            }
195
        }
196
        return false;
197
    }
198
}
199
200
if (!function_exists('str_contains')) {
201
    /**
202
     * Determine if a given string contains a given substring.
203
     *
204
     * @param  string $haystack
205
     * @param  string|array $needles
206
     * @return bool
207
     */
208
    function str_contains($haystack, $needles)
209
    {
210
        foreach ((array)$needles as $needle) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
211
            if ($needle != '' && strpos($haystack, $needle) !== false) {
212
                return true;
213
            }
214
        }
215
        return false;
216
    }
217
}
218
219
if (!function_exists('str_finish')) {
220
    /**
221
     * Cap a string with a single instance of a given value.
222
     *
223
     * @param  string $value
224
     * @param  string $cap
225
     * @return string
226
     */
227
    function str_finish($value, $cap)
228
    {
229
        $quoted = preg_quote($cap, '/');
230
        return preg_replace('/(?:' . $quoted . ')+$/', '', $value) . $cap;
231
    }
232
}
233
234
if (!function_exists('str_is')) {
235
    /**
236
     * Determine if a given string matches a given pattern.
237
     *
238
     * @param  string $pattern
239
     * @param  string $value
240
     * @return bool
241
     */
242
    function str_is($pattern, $value)
243
    {
244
        if ($pattern == $value) {
245
            return true;
246
        }
247
        $pattern = preg_quote($pattern, '#');
248
        // Asterisks are translated into zero-or-more regular expression wildcards
249
        // to make it convenient to check if the strings starts with the given
250
        // pattern such as "library/*", making any string check convenient.
251
        $pattern = str_replace('\*', '.*', $pattern) . '\z';
252
        return preg_match('#^' . $pattern . '#', $value) === 1;
253
    }
254
}
255
if (!function_exists('str_limit')) {
256
    /**
257
     * Limit the number of characters in a string.
258
     *
259
     * @param  string $value
260
     * @param  int $limit
261
     * @param  string $end
262
     * @return string
263
     */
264
    function str_limit($value, $limit = 100, $end = '...')
265
    {
266
        if (mb_strlen($value) <= $limit) {
267
            return $value;
268
        }
269
        return rtrim(mb_substr($value, 0, $limit, 'UTF-8')) . $end;
270
    }
271
}
272
273
if (!function_exists('str_replace_array')) {
274
    /**
275
     * Replace a given value in the string sequentially with an array.
276
     *
277
     * @param  string $search
278
     * @param  array $replace
279
     * @param  string $subject
280
     * @return string
281
     */
282
    function str_replace_array($search, array $replace, $subject)
283
    {
284
        foreach ($replace as $value) {
285
            $subject = preg_replace('/' . $search . '/', $value, $subject, 1);
286
        }
287
        return $subject;
288
    }
289
}
290
291
if (!function_exists('studly_case')) {
292
    /**
293
     * Convert a value to studly caps case.
294
     *
295
     * @param  string $value
296
     * @return string
297
     */
298
    function studly_case($value)
299
    {
300
        $studlyCache = [];
301
        $key = $value;
302
        if (isset($studlyCache[$key])) {
303
            return $studlyCache[$key];
304
        }
305
        $value = ucwords(str_replace(array('-', '_'), ' ', $value));
306
        return $studlyCache[$key] = str_replace(' ', '', $value);
307
    }
308
}
309
310
if (!function_exists('studly')) {
311
    /**
312
     * Convert a value to studly caps case.
313
     * Alias of studly_case
314
     *
315
     * @param  string $value
316
     * @return string
317
     */
318
    function studly($value)
319
    {
320
        return studly_case($value);
321
    }
322
}
323
324
if (!function_exists('camel_case')) {
325
    /**
326
     * Convert a value to camel case.
327
     *
328
     * @param  string $value
329
     * @return string
330
     */
331
    function camel_case($value)
332
    {
333
        $camelCache = [];
334
        if (isset($camelCache[$value])) {
335
            return $camelCache[$value];
336
        }
337
        return $camelCache[$value] = lcfirst(studly($value));
338
    }
339
}
340
341
/**
342
 * Replace underscores with dashes in the string.
343
 * @param string $word
344
 * @return string
345
 */
346
function underscore2dash(string $word) : string
347
{
348
    return str_replace('_', '-', $word);
349
}
350
351
/**
352
 * Make an underscored, lowercase form from the expression in the string.
353
 * @param string $word
354
 * @return string
355
 */
356
function dash2underscore(string $word) : string
357
{
358
    $word = preg_replace('/([A-Z]+)([A-Z][a-z])/', '\1_\2', $word);
359
    $word = preg_replace('/([a-z])([A-Z])/', '\1_\2', $word);
360
    return str_replace('-', '_', strtolower($word));
361
}
362
363
/**
364
 * Replace multiple spaces with one space.
365
 * @param string $str
366
 * @return string
367
 */
368
function str_replace_multiple_space(string $str) : string
369
{
370
    return preg_replace('/\s+/', ' ', $str);
371
}
372
373
/**
374
 * Replace last occurrence ($search) of a string ($subject) with $replace string.
375
 * @param string $search
376
 * @param string $replace
377
 * @param string $subject
378
 * @return string
379
 */
380
function str_replace_last(string $search, string $replace, string $subject) : string
381
{
382
    if ($search == '') {
383
        return $subject;
384
    }
385
    $position = strrpos($subject, $search);
386
    if ($position === false) {
387
        return $subject;
388
    }
389
    return substr_replace($subject, $replace, $position, strlen($search));
390
}
391
392
/**
393
 * Get a segment from a string based on a delimiter.
394
 * Returns an empty string when the offset doesn't exist.
395
 * Use a negative index to start counting from the last element.
396
 *
397
 * @param string $delimiter
398
 * @param int $index
399
 * @param string $subject
400
 *
401
 * @return string
402
 * @see https://github.com/spatie/string/blob/master/src/Str.php
403
 */
404
function segment($delimiter, $index, $subject)
405
{
406
    $segments = explode($delimiter, $subject);
407
    if ($index < 0) {
408
        $segments = array_reverse($segments);
409
        $index = (int)abs($index) - 1;
410
    }
411
    $segment = isset($segments[$index]) ? $segments[$index] : '';
412
    return $segment;
413
}
414
415
/**
416
 * Get the first segment from a string based on a delimiter.
417
 *
418
 * @param string $delimiter
419
 * @param string $subject
420
 *
421
 * @return string
422
 * @see https://github.com/spatie/string/blob/master/src/Str.php
423
 */
424
function firstSegment($delimiter, $subject) : string
425
{
426
    return segment($delimiter, 0, $subject);
427
}
428
429
/**
430
 * Get the last segment from a string based on a delimiter.
431
 *
432
 * @param string $delimiter
433
 * @param string $subject
434
 *
435
 * @return string
436
 * @see https://github.com/spatie/string/blob/master/src/Str.php
437
 */
438
function lastSegment($delimiter, $subject) : string
439
{
440
    return segment($delimiter, -1, $subject);
441
}
442
443
/**
444
 * Return true if $subject is null or empty string ('').
445
 * @param $subject
446
 * @return bool
447
 */
448
function isNullOrEmpty($subject) : bool
449
{
450
    return $subject === null || $subject == '';
451
}
452
453
/**
454
 * Return true if $subject is not null and is not empty string ('').
455
 * @param $subject
456
 * @return bool
457
 */
458
function isNotNullOrEmpty($subject) : bool
459
{
460
    return !isNullOrEmpty($subject);
461
}
462