Completed
Push — master ( 35e698...79f205 )
by Lorenzo
02:08
created

string.php ➔ dash2underscore()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 6
rs 9.4285
1
<?php
2
3
/**
4
 * Strip new line breaks from a string
5
 * @param $str
6
 * @return string|array
7
 */
8
function strip_nl($str)
9
{
10
    return str_replace("\n", "", str_replace("\r", "", $str));
11
}
12
13
/**
14
 * Generate random string from [0-9A-Za-z] charset.
15
 * You may extend charset by passing $extChars.
16
 * Ex.: $extChars='-_&$!+'
17
 * @param int $length
18
 * @param string $extChars
19
 * @return string
20
 */
21
function generateRandomString(int $length = 10, string $extChars = '') : string
22
{
23
    if ($length < 1) {
24
        $length = 1;
25
    }
26
27
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
28
    if ($extChars !== null && $extChars != '') {
29
        $characters .= $extChars;
30
    }
31
32
    $charactersLength = strlen($characters);
33
    $randomString = '';
34
35
    for ($i = 0; $i < $length; $i++) {
36
        $randomString .= $characters[random_int(0, $charactersLength - 1)];
37
    }
38
39
    return $randomString;
40
}
41
42
/**
43
 * Javascript escape
44
 * @param string $str
45
 * @return string
46
 * @source https://github.com/rtconner/laravel-plusplus/blob/laravel-5/src/plus-functions.php
47
 */
48
function jse(string $str) : string
49
{
50
    if ($str === null || $str == '') {
51
        return '';
52
    }
53
    $str = str_replace("\n", "", str_replace("\r", "", $str));
54
    return addslashes($str);
55
}
56
57
if (!function_exists('gravatar')) {
58
    /**
59
     * Get a Gravatar URL from email.
60
     *
61
     * @param string $email The email address
62
     * @param int $size in pixels, defaults to 80px [ 1 - 2048 ]
63
     * @param string $default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
64
     * @param string $rating (inclusive) [ g | pg | r | x ]
65
     * @return string
66
     * @source http://gravatar.com/site/implement/images/php/
67
     */
68
    function gravatar($email, $size = 80, $default = 'mm', $rating = 'g')
69
    {
70
        $url = 'http://www.gravatar.com/avatar/';
71
        $url .= md5(strtolower(trim($email)));
72
        $url .= "?s=$size&d=$default&r=$rating";
73
        return $url;
74
    }
75
}
76
77
/**
78
 * *****************************************************
79
 * LARAVEL STRING HELPERS
80
 * With some adjustments
81
 * *****************************************************
82
 */
83
84
if (!function_exists('e')) {
85
    /**
86
     * Escape HTML entities in a string.
87
     *
88
     * @param  string $value
89
     * @return string
90
     */
91
    function e($value)
92
    {
93
        return htmlentities($value, ENT_QUOTES, 'UTF-8', false);
94
    }
95
}
96
97
if (!function_exists('preg_replace_sub')) {
98
    /**
99
     * Replace a given pattern with each value in the array in sequentially.
100
     *
101
     * @param  string $pattern
102
     * @param  array $replacements
103
     * @param  string $subject
104
     * @return string
105
     */
106
    function preg_replace_sub($pattern, &$replacements, $subject)
107
    {
108
        return preg_replace_callback($pattern, function () use (&$replacements) {
109
            return array_shift($replacements);
110
        }, $subject);
111
    }
112
}
113
114
if (!function_exists('snake_case')) {
115
    /**
116
     * Convert a string to snake case.
117
     *
118
     * @param  string $value
119
     * @param  string $delimiter
120
     * @return string
121
     */
122
    function snake_case($value, $delimiter = '_')
123
    {
124
        $snakeCache = [];
125
        $key = $value . $delimiter;
126
        if (isset($snakeCache[$key])) {
127
            return $snakeCache[$key];
128
        }
129
        if (!ctype_lower($value)) {
130
            $value = strtolower(preg_replace('/(.)(?=[A-Z])/', '$1' . $delimiter, $value));
131
        }
132
        return $snakeCache[$key] = $value;
133
    }
134
}
135
136
if (!function_exists('str_random')) {
137
    /**
138
     * Generate a more truly "random" alpha-numeric string with openssl.
139
     * If openssl_random_pseudo_bytes not exists, use simple legacy function
140
     *
141
     * @param  int $length
142
     * @return string
143
     *
144
     * @throws \RuntimeException
145
     */
146
    function str_random(int $length = 16)
147
    {
148
        if ($length < 0) {
149
            $length = 16;
150
        }
151
152
        if (!function_exists('openssl_random_pseudo_bytes')) {
153
            return generateRandomString($length);
154
        }
155
        $bytes = openssl_random_pseudo_bytes($length * 2);
156
        if ($bytes === false) {
157
            throw new RuntimeException('Unable to generate random string.');
158
        }
159
        return substr(str_replace(array('/', '+', '='), '', base64_encode($bytes)), 0, $length);
160
    }
161
}
162
163
if (!function_exists('ends_with')) {
164
    /**
165
     * Determine if a given string ends with a given substring.
166
     *
167
     * @param  string $haystack
168
     * @param  string|array $needles
169
     * @return bool
170
     */
171
    function ends_with($haystack, $needles)
172
    {
173 View Code Duplication
        if ($haystack === null || $haystack == '' || $needles === null || $needles == '') {
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...
174
            return false;
175
        }
176
177
        foreach ((array)$needles as $needle) {
178
            if ((string)$needle === substr($haystack, -strlen($needle))) {
179
                return true;
180
            }
181
        }
182
        return false;
183
    }
184
}
185
186
if (!function_exists('starts_with')) {
187
    /**
188
     * Determine if a given string starts with a given substring.
189
     *
190
     * @param  string $haystack
191
     * @param  string|array $needles
192
     * @return bool
193
     */
194
    function starts_with($haystack, $needles)
195
    {
196 View Code Duplication
        if ($haystack === null || $haystack == '' || $needles === null || $needles == '') {
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...
197
            return false;
198
        }
199
200 View Code Duplication
        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...
201
            if ($needle != '' && strpos($haystack, $needle) === 0) {
202
                return true;
203
            }
204
        }
205
        return false;
206
    }
207
}
208
209
if (!function_exists('str_contains')) {
210
    /**
211
     * Determine if a given string contains a given substring.
212
     *
213
     * @param  string $haystack
214
     * @param  string|array $needles
215
     * @return bool
216
     */
217
    function str_contains($haystack, $needles)
218
    {
219 View Code Duplication
        foreach ((array)$needles as $needle) {
1 ignored issue
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...
220
            if ($needle != '' && strpos($haystack, $needle) !== false) {
221
                return true;
222
            }
223
        }
224
        return false;
225
    }
226
}
227
228
if (!function_exists('str_finish')) {
229
    /**
230
     * Cap a string with a single instance of a given value.
231
     *
232
     * @param  string $value
233
     * @param  string $cap
234
     * @return string
235
     */
236
    function str_finish($value, $cap)
237
    {
238
        $quoted = preg_quote($cap, '/');
239
        return preg_replace('/(?:' . $quoted . ')+$/', '', $value) . $cap;
240
    }
241
}
242
243
if (!function_exists('str_is')) {
244
    /**
245
     * Determine if a given string matches a given pattern.
246
     *
247
     * @param  string $pattern
248
     * @param  string $value
249
     * @return bool
250
     */
251
    function str_is($pattern, $value)
252
    {
253
        if ($pattern == $value) {
254
            return true;
255
        }
256
        $pattern = preg_quote($pattern, '#');
257
        // Asterisks are translated into zero-or-more regular expression wildcards
258
        // to make it convenient to check if the strings starts with the given
259
        // pattern such as "library/*", making any string check convenient.
260
        $pattern = str_replace('\*', '.*', $pattern) . '\z';
261
        return (bool)preg_match('#^' . $pattern . '#', $value);
262
    }
263
}
264
if (!function_exists('str_limit')) {
265
    /**
266
     * Limit the number of characters in a string.
267
     *
268
     * @param  string $value
269
     * @param  int $limit
270
     * @param  string $end
271
     * @return string
272
     */
273
    function str_limit($value, $limit = 100, $end = '...')
274
    {
275
        if (mb_strlen($value) <= $limit) {
276
            return $value;
277
        }
278
        return rtrim(mb_substr($value, 0, $limit, 'UTF-8')) . $end;
279
    }
280
}
281
282
if (!function_exists('str_replace_array')) {
283
    /**
284
     * Replace a given value in the string sequentially with an array.
285
     *
286
     * @param  string $search
287
     * @param  array $replace
288
     * @param  string $subject
289
     * @return string
290
     */
291
    function str_replace_array($search, array $replace, $subject)
292
    {
293
        foreach ($replace as $value) {
294
            $subject = preg_replace('/' . $search . '/', $value, $subject, 1);
295
        }
296
        return $subject;
297
    }
298
}
299
300
if (!function_exists('studly_case')) {
301
    /**
302
     * Convert a value to studly caps case.
303
     *
304
     * @param  string $value
305
     * @return string
306
     */
307
    function studly_case($value)
308
    {
309
        $studlyCache = [];
310
        $key = $value;
311
        if (isset($studlyCache[$key])) {
312
            return $studlyCache[$key];
313
        }
314
        $value = ucwords(str_replace(array('-', '_'), ' ', $value));
315
        return $studlyCache[$key] = str_replace(' ', '', $value);
316
    }
317
}
318
319
if (!function_exists('studly')) {
320
    /**
321
     * Convert a value to studly caps case.
322
     * Alias of studly_case
323
     *
324
     * @param  string $value
325
     * @return string
326
     */
327
    function studly($value)
328
    {
329
        return studly_case($value);
330
    }
331
}
332
333
if (!function_exists('camel_case')) {
334
    /**
335
     * Convert a value to camel case.
336
     *
337
     * @param  string $value
338
     * @return string
339
     */
340
    function camel_case($value)
341
    {
342
        $camelCache = [];
343
        if (isset($camelCache[$value])) {
344
            return $camelCache[$value];
345
        }
346
        return $camelCache[$value] = lcfirst(studly($value));
347
    }
348
}
349
350
/**
351
 * Replace underscores with dashes in the string.
352
 * @param string $word
353
 * @return string
354
 */
355
function underscore2dash(string $word) : string
356
{
357
    return str_replace('_', '-', $word);
358
}
359
360
/**
361
 * Make an underscored, lowercase form from the expression in the string.
362
 * @param string $word
363
 * @return string
364
 */
365
function dash2underscore(string $word) : string
366
{
367
    $word = preg_replace('/([A-Z]+)([A-Z][a-z])/', '\1_\2', $word);
368
    $word = preg_replace('/([a-z])([A-Z])/', '\1_\2', $word);
369
    return str_replace('-', '_', strtolower($word));
370
}
371