Passed
Push — master ( a47c69...06a586 )
by Stephen
05:58
created

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