Passed
Push — master ( 86ceb8...b6e5e7 )
by Stephen
05:58
created

StringHelpers::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
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
     * @return string
59
     */
60
    public function id(): string
61
    {
62
        return strtolower(
63
            str_replace(' ', '-', str_replace('&', '-', $this->string))
64
        );
65
    }
66
67
    /**
68
     * Remove ' ', '-', '&' characters.
69
     *
70
     * @return string
71
     */
72
    public function strip(): string
73
    {
74
        return strtolower(
75
            str_replace(
76
                ',', '', str_replace(
77
                    ' ', '-', str_replace(
78
                        '&',
79
                        '',
80
                        $this->string
81
                    )
82
                )
83
            )
84
        );
85
    }
86
87
    /**
88
     * Check if a needle string is in a haystack string.
89
     *
90
     * @param string|array $needle
91
     * @param string $boolean
92
     * @return bool
93
     */
94
    public function inString($needle, string $boolean = 'and'): bool
95
    {
96
        // Determine if an array of $needle's was passed
97
        if (is_array($needle)) {
98
99
            // Check if each of the needles is found in the haystack
100
            $results = [];
101
            foreach($needle as $need) {
102
                $results[] = $this->isNeedleInString($need);
103
            }
104
105
            // Determine if any of the needles can exist to return true
106
            if ($boolean == 'or') {
107
                return in_array(true, $results);
108
            }
109
110
            // All needles must be found
111
            else {
112
                return arrayValuesEqual($results, true);
113
            }
114
        }
115
        return $this->isNeedleInString($needle);
116
    }
117
118
    /**
119
     * Check if a needle exists inside a haystack
120
     *
121
     * @param $needle
122
     * @return bool
123
     */
124
    private function isNeedleInString($needle): bool
125
    {
126
        return strpos($this->string, $needle) !== false;
127
    }
128
129
    /**
130
     * Determine if the $string is a plain text list of values.
131
     *
132
     *  - if $string is a list, an array of values is returned
133
     *  - if $sting is a string, false is returned
134
     *
135
     * @param array|string[] $separators
136
     * @return bool|false|string[]
137
     */
138
    public function isListString(array $separators = [', ', ' '])
139
    {
140
        foreach ($separators as $needle) {
141
            // If the $needle is found in the $string
142
            // we know the string is a plain text list
143
            // so an array of values is returned
144
            if ($this->inString($needle)) {
145
                return explode($needle, $this->string);
146
            }
147
        }
148
149
        // If none of the separators are found
150
        // we know the string is not a list
151
        return false;
152
    }
153
154
    /**
155
     * Explode a string using an array of delimiters instead of a single string.
156
     *
157
     * @param array|string[] $delimiters
158
     * @param string $replacer
159
     * @return array
160
     */
161
    public function explodeMany(array $delimiters = [',', '&', '/', '-'], string $replacer = '***'): array
162
    {
163
        // Replace all of $delimiters chars with the
164
        // $replacer so that a single delimiter can
165
        // be used to explode the string
166
        $cleaned = str_replace($delimiters, $replacer, $this->string);
167
168
        // Use the replacer as the $delimiter
169
        // since it has replaced each of the
170
        // passed $delimiters
171
        $split = explode($replacer, $cleaned);
172
173
        // Utilize collection's if laravel/framework is installed
174
        if (function_exists('collect')) {
175
            // Collect the array of strings
176
            return collect($split)
177
178
                // Remove empty strings from the collection
179
                ->filter(function (string $item) {
180
                    return strlen($item) > 0;
181
                })
182
183
                // Trim the remaining strings in the collection
184
                ->map(function (string $item) {
185
                    return trim($item);
186
                })
187
188
                // Encode as array
189
                ->toArray();
190
        }
191
192
        // Use built in array functions
193
        else {
194
            // Remove empty strings from the collection
195
            $filtered = array_filter($split, function (string $item) {
196
                return strlen($item) > 0;
197
            });
198
199
            // Trim the remaining strings in the collection
200
            return  array_map(function (string $item) {
201
                return trim($item);
202
            }, $filtered);
203
        }
204
    }
205
206
    /**
207
     * Add whitespace padding to a string.
208
     *
209
     * @param int $amount
210
     * @param string $pad
211
     * @param bool $front add whitespace to 'front' of the string
212
     * @param bool $back add whitespace to the 'back' of the string
213
     * @return string
214
     */
215
    public function whitespacePad(int $amount = 1,
216
                                  string $pad = ' ',
217
                                  bool $front = true,
218
                                  bool $back = true): string
219
    {
220
        // Multiple $pad chars by $amount
221
        $whitespace = str_repeat($pad, $amount);
222
223
        // Return string with padding
224
        return ($front ? $whitespace : '').$this->string.($back ? $whitespace : '');
225
    }
226
227
    /**
228
     * Add whitespace padding to only the 'back' of the string.
229
     *
230
     * @param int $amount
231
     * @param string $pad
232
     * @return string
233
     */
234
    public function whitespacePadBack(int $amount = 1, string $pad = ' '): string
235
    {
236
        return $this->whitespacePad($amount, $pad, false, true);
237
    }
238
239
    /**
240
     * Add whitespace padding to only the 'back' of the string.
241
     *
242
     * @param int $amount
243
     * @param string $pad
244
     * @return string
245
     */
246
    public function whitespacePadFront(int $amount = 1, string $pad = ' '): string
247
    {
248
        return $this->whitespacePad($amount, $pad, true, false);
249
    }
250
}
251