Passed
Push — master ( 924cd6...bbbdac )
by Stephen
02:28
created

StringHelpers::whitespaceReplace()   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 1
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
     * Remove illegal characters from a string to create an ID.
62
     *
63
     *  - legal chars: '&', ' '
64
     *
65
     * @return string
66
     */
67
    public function id(): string
68
    {
69
        // todo: improve this by removing repeated '-'
70
        return strtolower(
71
            str_replace(' ', '-', str_replace('&', '-', $this->string))
72
        );
73
    }
74
75
    /**
76
     * Remove ' ', '-', '&' characters.
77
     *
78
     * @return string
79
     */
80
    public function strip(): string
81
    {
82
        // todo: maybe replace with id & make depreciated?
83
        return strtolower(
84
            str_replace(
85
                ',', '', str_replace(
86
                    ' ', '-', str_replace(
87
                        '&',
88
                        '',
89
                        $this->string
90
                    )
91
                )
92
            )
93
        );
94
    }
95
96
    /**
97
     * Check if a needle string is in a haystack string.
98
     *
99
     *  $boolean param determines weather ALL or ANY of $needles
100
     *  need to be found to return true (only when $needle is an array).
101
     *
102
     *  todo: rename given $needle can be an array
103
     *
104
     * @param string|array $needle
105
     * @param string $boolean
106
     * @return bool
107
     */
108
    public function inString($needle, string $boolean = 'and'): bool
109
    {
110
        // Determine if an array of $needle's was passed
111
        if (is_array($needle)) {
112
113
            // Check if each of the needles is found in the haystack
114
            $results = [];
115
            foreach ($needle as $need) {
116
                $results[] = $this->isNeedleInString($need);
117
            }
118
119
            // Determine if any of the needles can exist to return true
120
            if ($boolean == 'or') {
121
                return in_array(true, $results);
122
            }
123
124
            // All needles must be found
125
            else {
126
                return (new ArrayHelpers($results))->arrayValuesEqual(true);
127
            }
128
        }
129
130
        return $this->isNeedleInString($needle);
131
    }
132
133
    /**
134
     * Check if a needle exists inside a haystack.
135
     *
136
     * @param $needle
137
     * @return bool
138
     */
139
    private function isNeedleInString($needle): bool
140
    {
141
        return strpos($this->string, $needle) !== false;
142
    }
143
144
    /**
145
     * Determine if the $string is a plain text list of values.
146
     *
147
     *  - if $string is a list, an array of values is returned
148
     *  - if $sting is a string, false is returned
149
     *
150
     *  todo: refactor to listString?
151
     *
152
     * @param array|string[] $separators
153
     * @return bool|false|string[]
154
     */
155
    public function isListString(array $separators = [', ', ' '])
156
    {
157
        foreach ($separators as $needle) {
158
            // If the $needle is found in the $string
159
            // we know the string is a plain text list
160
            // so an array of values is returned
161
            if ($this->inString($needle)) {
162
                // todo: use explode many?
163
                return explode($needle, $this->string);
164
            }
165
        }
166
167
        // If none of the separators are found
168
        // we know the string is not a list
169
        return false;
170
    }
171
172
    /**
173
     * Explode a string using an array of delimiters instead of a single string.
174
     *
175
     * @param array|string[] $delimiters
176
     * @param string $replacer
177
     * @return array
178
     */
179
    public function explodeMany(array $delimiters = [',', '&', '/', '-'], string $replacer = '***'): array
180
    {
181
        // Replace all of $delimiters chars with the
182
        // $replacer so that a single delimiter can
183
        // be used to explode the string
184
        $cleaned = str_replace($delimiters, $replacer, $this->string);
185
186
        // Use the replacer as the $delimiter
187
        // since it has replaced each of the
188
        // passed $delimiters
189
        $split = explode($replacer, $cleaned);
190
191
        // Utilize collection's if laravel/framework is installed
192
        if (function_exists('collect')) {
193
            // Collect the array of strings
194
            return collect($split)
195
196
                // Remove empty strings from the collection
197
                ->filter(function (string $item) {
198
                    return strlen($item) > 0;
199
                })
200
201
                // Trim the remaining strings in the collection
202
                ->map(function (string $item) {
203
                    return trim($item);
204
                })
205
206
                // Encode as array
207
                ->toArray();
208
        }
209
210
        // Use built in array functions
211
        else {
212
            // Remove empty strings from the collection
213
            $filtered = array_filter($split, function (string $item) {
214
                return strlen($item) > 0;
215
            });
216
217
            // Trim the remaining strings in the collection
218
            return  array_map(function (string $item) {
219
                return trim($item);
220
            }, $filtered);
221
        }
222
    }
223
224
    /**
225
     * Add whitespace padding to a string.
226
     *
227
     * @param int $amount
228
     * @param string $pad
229
     * @param bool $front add whitespace to 'front' of the string
230
     * @param bool $back add whitespace to the 'back' of the string
231
     * @return string
232
     */
233
    public function whitespacePad(int $amount = 1,
234
                                  string $pad = ' ',
235
                                  bool $front = true,
236
                                  bool $back = true): string
237
    {
238
        // Multiple $pad chars by $amount
239
        $whitespace = str_repeat($pad, $amount);
240
241
        // Return string with padding
242
        return ($front ? $whitespace : '').$this->string.($back ? $whitespace : '');
243
    }
244
245
    /**
246
     * Add whitespace padding to only the 'back' of the string.
247
     *
248
     * @param int $amount
249
     * @param string $pad
250
     * @return string
251
     */
252
    public function whitespacePadBack(int $amount = 1, string $pad = ' '): string
253
    {
254
        return $this->whitespacePad($amount, $pad, false, true);
255
    }
256
257
    /**
258
     * Add whitespace padding to only the 'back' of the string.
259
     *
260
     * @param int $amount
261
     * @param string $pad
262
     * @return string
263
     */
264
    public function whitespacePadFront(int $amount = 1, string $pad = ' '): string
265
    {
266
        return $this->whitespacePad($amount, $pad, true, false);
267
    }
268
269
    /**
270
     * Remove all whitespace (spaces) from a string.
271
     *
272
     * @return string
273
     */
274
    public function whitespaceRemove(): string
275
    {
276
        return $this->whitespaceReplace();
277
    }
278
279
    /**
280
     * Remove all whitespace (spaces) from a string & replace with another string.
281
     *
282
     * @param string $replacement defaults to ''
283
     * @return string
284
     */
285
    public function whitespaceReplace(string $replacement = ''): string
286
    {
287
        return str_replace(' ', $replacement, $this->string);
288
    }
289
290
    /**
291
     * Fill a string with whitespace in order to make it a certain length in chars.
292
     *
293
     * @param int $length length of the string in characters
294
     * @param string $filler string to use to fill the needed whitespace
295
     * @return string
296
     */
297
    public function fill(int $length, string $filler = ' '): string
298
    {
299
        return $this->string . str_repeat($filler, $length - strlen($this->string));
300
    }
301
}
302