Passed
Push — master ( 1d6f63...bde0a3 )
by Stephen
10:28
created

StringHelpers::camelCaseSplit()   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 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Sfneal\Helpers\Strings;
4
5
use Sfneal\Helpers\Arrays\ArrayHelpers;
6
use Sfneal\Helpers\Strings\Traits\StaticMethods;
7
8
class StringHelpers
9
{
10
    use StaticMethods;
11
12
    /**
13
     * @var string
14
     */
15
    private $string;
16
17
    /**
18
     * StringHelpers constructor.
19
     *
20
     * @param string $string
21
     */
22
    public function __construct(string $string)
23
    {
24
        $this->string = $string;
25
    }
26
27
    /**
28
     * Sanitize a file name to remove illegal chars.
29
     *
30
     * @return string
31
     */
32
    public function sanitizeFileName(): string
33
    {
34
        return preg_replace('/[^A-Za-z0-9_\-]/', '_', $this->string);
35
    }
36
37
    /**
38
     * Truncate a string to be no longer than $chars.
39
     *
40
     * @param int $chars
41
     * @param string $suffix
42
     * @return string
43
     */
44
    public function truncate(int $chars = 100, string $suffix = '...'): string
45
    {
46
        return (strlen($this->string) <= $chars) ? $this->string : substr($this->string, 0, $chars).$suffix;
47
    }
48
49
    /**
50
     * Covert a camel cased string into a $char separated string.
51
     *
52
     * @param string $char
53
     * @return string
54
     */
55
    public function camelCaseConvert(string $char = '-'): string
56
    {
57
        return strtolower(preg_replace('/(?<!^)[A-Z]/', $char.'$0', $this->string));
58
    }
59
60
    /**
61
     * Explode a string using upper case chars as the separator.
62
     *
63
     * @return array
64
     */
65
    public function camelCaseSplit(): array
66
    {
67
        return preg_split('/(?=[A-Z])/', $this->string, -1, PREG_SPLIT_NO_EMPTY);
68
    }
69
70
    /**
71
     * Remove illegal characters from a string to create an ID.
72
     *
73
     *  - legal chars: '&', ' '
74
     *
75
     * @return string
76
     */
77
    public function id(): string
78
    {
79
        // todo: improve this by removing repeated '-'
80
        return strtolower(
81
            str_replace(' ', '-', str_replace('&', '-', $this->string))
82
        );
83
    }
84
85
    /**
86
     * Remove ' ', '-', '&' characters.
87
     *
88
     * @return string
89
     */
90
    public function strip(): string
91
    {
92
        // todo: maybe replace with id & make depreciated?
93
        return strtolower(
94
            str_replace(
95
                ',', '', str_replace(
96
                    ' ', '-', str_replace(
97
                        '&',
98
                        '',
99
                        $this->string
100
                    )
101
                )
102
            )
103
        );
104
    }
105
106
    /**
107
     * Check if a needle string is in a haystack string.
108
     *
109
     *  $boolean param determines weather ALL or ANY of $needles
110
     *  need to be found to return true (only when $needle is an array).
111
     *
112
     *  todo: rename given $needle can be an array
113
     *
114
     * @param string|array $needle
115
     * @param string $boolean
116
     * @return bool
117
     */
118
    public function inString($needle, string $boolean = 'and'): bool
119
    {
120
        // Determine if an array of $needle's was passed
121
        if (is_array($needle)) {
122
123
            // Check if each of the needles is found in the haystack
124
            $results = [];
125
            foreach ($needle as $need) {
126
                $results[] = $this->isNeedleInString($need);
127
            }
128
129
            // Determine if any of the needles can exist to return true
130
            if ($boolean == 'or') {
131
                return in_array(true, $results);
132
            }
133
134
            // All needles must be found
135
            else {
136
                return (new ArrayHelpers($results))->arrayValuesEqual(true);
137
            }
138
        }
139
140
        return $this->isNeedleInString($needle);
141
    }
142
143
    /**
144
     * Check if a needle exists inside a haystack.
145
     *
146
     * @param $needle
147
     * @return bool
148
     */
149
    private function isNeedleInString($needle): bool
150
    {
151
        return strpos($this->string, $needle) !== false;
152
    }
153
154
    /**
155
     * Determine if the $string is a plain text list of values.
156
     *
157
     *  - if $string is a list, an array of values is returned
158
     *  - if $sting is a string, false is returned
159
     *
160
     *  todo: refactor to listString?
161
     *
162
     * @param array|string[] $separators
163
     * @return bool|false|string[]
164
     */
165
    public function isListString(array $separators = [', ', ' '])
166
    {
167
        foreach ($separators as $needle) {
168
            // If the $needle is found in the $string
169
            // we know the string is a plain text list
170
            // so an array of values is returned
171
            if ($this->inString($needle)) {
172
                // todo: use explode many?
173
                return explode($needle, $this->string);
174
            }
175
        }
176
177
        // If none of the separators are found
178
        // we know the string is not a list
179
        return false;
180
    }
181
182
    /**
183
     * Explode a string using an array of delimiters instead of a single string.
184
     *
185
     * @param array|string[] $delimiters
186
     * @param string $replacer
187
     * @return array
188
     */
189
    public function explodeMany(array $delimiters = [',', '&', '/', '-'], string $replacer = '***'): array
190
    {
191
        // Replace all of $delimiters chars with the
192
        // $replacer so that a single delimiter can
193
        // be used to explode the string
194
        $cleaned = str_replace($delimiters, $replacer, $this->string);
195
196
        // Use the replacer as the $delimiter
197
        // since it has replaced each of the
198
        // passed $delimiters
199
        $split = explode($replacer, $cleaned);
200
201
        // Utilize collection's if laravel/framework is installed
202
        if (function_exists('collect')) {
203
            // Collect the array of strings
204
            return collect($split)
205
206
                // Remove empty strings from the collection
207
                ->filter(function (string $item) {
208
                    return strlen($item) > 0;
209
                })
210
211
                // Trim the remaining strings in the collection
212
                ->map(function (string $item) {
213
                    return trim($item);
214
                })
215
216
                // Encode as array
217
                ->toArray();
218
        }
219
220
        // Use built in array functions
221
        else {
222
            // Remove empty strings from the collection
223
            $filtered = array_filter($split, function (string $item) {
224
                return strlen($item) > 0;
225
            });
226
227
            // Trim the remaining strings in the collection
228
            return  array_map(function (string $item) {
229
                return trim($item);
230
            }, $filtered);
231
        }
232
    }
233
234
    /**
235
     * Add whitespace padding to a string.
236
     *
237
     * @param int $amount
238
     * @param string $pad
239
     * @param bool $front add whitespace to 'front' of the string
240
     * @param bool $back add whitespace to the 'back' of the string
241
     * @return string
242
     */
243
    public function whitespacePad(int $amount = 1,
244
                                  string $pad = ' ',
245
                                  bool $front = true,
246
                                  bool $back = true): string
247
    {
248
        // Multiple $pad chars by $amount
249
        $whitespace = str_repeat($pad, $amount);
250
251
        // Return string with padding
252
        return ($front ? $whitespace : '').$this->string.($back ? $whitespace : '');
253
    }
254
255
    /**
256
     * Add whitespace padding to only the 'back' of the string.
257
     *
258
     * @param int $amount
259
     * @param string $pad
260
     * @return string
261
     */
262
    public function whitespacePadBack(int $amount = 1, string $pad = ' '): string
263
    {
264
        return $this->whitespacePad($amount, $pad, false, true);
265
    }
266
267
    /**
268
     * Add whitespace padding to only the 'back' of the string.
269
     *
270
     * @param int $amount
271
     * @param string $pad
272
     * @return string
273
     */
274
    public function whitespacePadFront(int $amount = 1, string $pad = ' '): string
275
    {
276
        return $this->whitespacePad($amount, $pad, true, false);
277
    }
278
279
    /**
280
     * Remove all whitespace (spaces) from a string.
281
     *
282
     * @return string
283
     */
284
    public function whitespaceRemove(): string
285
    {
286
        return $this->whitespaceReplace();
287
    }
288
289
    /**
290
     * Remove all whitespace (spaces) from a string & replace with another string.
291
     *
292
     * @param string $replacement defaults to ''
293
     * @return string
294
     */
295
    public function whitespaceReplace(string $replacement = ''): string
296
    {
297
        return str_replace(' ', $replacement, $this->string);
298
    }
299
300
    /**
301
     * Fill a string with whitespace in order to make it a certain length in chars.
302
     *
303
     * @param int $length length of the string in characters
304
     * @param string $filler string to use to fill the needed whitespace
305
     * @return string
306
     */
307
    public function fill(int $length, string $filler = ' '): string
308
    {
309
        return $this->string.str_repeat($filler, $length - strlen($this->string));
310
    }
311
}
312