-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStr.hh
439 lines (372 loc) · 12.8 KB
/
Str.hh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
<?hh // strict
/**
* @copyright 2010-2015, The Titon Project
* @license http://opensource.org/licenses/bsd-license.php
* @link http://titon.io
*/
namespace Titon\Utility;
/**
* Specific methods that deal with string manipulation, truncation, formation, etc.
*
* @package Titon\Utility
*/
class Str {
/**
* Generator types.
*/
const string ALPHA = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
const string ALPHA_LOWER = 'abcdefghijklmnopqrstuvwxyz';
const string ALPHA_UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const string NUMERIC = '0123456789';
const string NUMERIC_NOZERO = '123456789';
const string NUMERIC_EVEN = '02468';
const string NUMERIC_ODD = '13579';
const string ALNUM = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
const string HEX = '0123456789abcdef';
/**
* Return the character at the specified index, if not found returns null.
*
* @param string $string
* @param int $index
* @return string
*/
public static function charAt(string $string, int $index): ?string {
return $string[$index] ?: null;
}
/**
* Compares to strings alphabetically. Returns 0 if they are equal, negative if passed value is greater, or positive if current value is greater.
*
* @param string $string
* @param string $value
* @param int $length
* @return int
*/
public static function compare(string $string, string $value, int $length = 0): int {
if ($length > 0) {
return strncasecmp($string, $value, $length);
}
return strcasecmp($string, $value);
}
/**
* Check to see if a string exists within this string.
*
* @param string $string
* @param string $needle
* @param bool $strict
* @param int $offset
* @return bool
*/
public static function contains(string $string, string $needle, bool $strict = true, int $offset = 0): bool {
return (static::indexOf($string, $needle, $strict, $offset) >= 0);
}
/**
* Checks to see if the string ends with a specific value.
*
* @param string $string
* @param string $needle
* @param bool $strict
* @return bool
*/
public static function endsWith(string $string, string $needle, bool $strict = true): bool {
$end = static::extract($string, -mb_strlen($needle));
if ($strict) {
return ($end === $needle);
}
return (mb_strtolower($end) === mb_strtolower($needle));
}
/**
* Extracts a portion of a string.
*
* @param string $string
* @param int $offset
* @param int $length
* @return string
*/
public static function extract(string $string, int $offset, int $length = 0): string {
if ($length) {
return mb_substr($string, $offset, $length);
}
return mb_substr($string, $offset);
}
/**
* Generates a string of random characters.
*
* @param int $length
* @param string $seed
* @return string
*/
public static function generate(int $length, string $seed = self::ALNUM): string {
$return = '';
$seed = (string) $seed;
$totalChars = mb_strlen($seed) - 1;
for ($i = 0; $i < $length; ++$i) {
$return .= $seed[rand(0, $totalChars)];
}
return $return;
}
/**
* Return a hashed string using one of the built in ciphers (md5, sha1, sha256, etc) and use the config salt if it has been set.
* Can also supply an optional second salt for increased security.
*
* @param string $cipher
* @param string $string
* @param string $salt
* @return string
*/
public static function hash(string $string, string $cipher, string $salt = ''): string {
return hash_hmac($cipher, $string, $salt);
}
/**
* Grab the index of the first matched character. Returns -1 when the needle is not found.
*
* @param string $string
* @param string $needle
* @param bool $strict
* @param int $offset
* @return int
*/
public static function indexOf(string $string, string $needle, bool $strict = true, int $offset = 0): int {
if ($strict) {
$index = mb_strpos($string, $needle, $offset);
} else {
$index = mb_stripos($string, $needle, $offset);
}
return ($index === false) ? -1 : $index;
}
/**
* Insert values into a string defined by an array of key tokens.
*
* @uses Titon\Utility\Sanitize
*
* @param string $string
* @param Map<Tk, Tv> $data
* @param \Titon\Utility\OptionMap $options {
* @var string $before Opening variable delimiter
* @var string $after Closing variable delimiter
* @var bool $escape Escape the string
* }
* @return string
*/
public static function insert<Tk, Tv>(string $string, Map<Tk, Tv> $data, OptionMap $options = Map {}): string {
$options = (Map {
'before' => '{',
'after' => '}',
'escape' => true
})->setAll($options);
foreach ($data as $key => $value) {
$string = str_replace((string) $options['before'] . (string) $key . (string) $options['after'], $value, $string);
}
if ($options['escape']) {
$string = Sanitize::escape($string);
}
return $string;
}
/**
* Grab the index of the last matched character. Returns -1 when the needle is not found.
*
* @param string $string
* @param string $needle
* @param bool $strict
* @param int $offset
* @return int
*/
public static function lastIndexOf(string $string, string $needle, bool $strict = true, int $offset = 0): int {
if ($strict) {
$index = mb_strrpos($string, $needle, $offset);
} else {
$index = mb_strripos($string, $needle, $offset);
}
return ($index === false) ? -1 : $index;
}
/**
* Creates a comma separated list with the last item having an ampersand prefixing it.
*
* @param Vector<string> $items
* @param string $glue
* @param string $sep
* @return string
*/
public static function listing(Vector<string> $items, string $glue = ' & ', string $sep = ', '): string {
$lastItem = $items->pop();
if ($items->count() === 0) {
return $lastItem;
}
$items = implode($sep, $items);
$items = $items . $glue . $lastItem;
return $items;
}
/**
* Scrambles the source of a string.
*
* @param string $string
* @return string
*/
public static function obfuscate(string $string): string {
$length = mb_strlen($string);
$scrambled = '';
if ($length > 0) {
for ($i = 0; $i < $length; $i++) {
$scrambled .= '&#' . ord($string[$i]) . ';';
}
}
return $scrambled;
}
/**
* If a string is too long, shorten it in the middle while also respecting whitespace and preserving words.
*
* @param string $string
* @param int $limit
* @param string $glue
* @return string
*/
public static function shorten(string $string, int $limit = 25, string $glue = ' … '): string {
if (mb_strlen($string) > $limit) {
$width = round($limit / 2);
// Prefix
$pre = mb_substr($string, 0, $width);
if (mb_substr($pre, -1) !== ' ' && ($i = static::lastIndexOf($pre, ' '))) {
if ($i >= 0) {
$pre = mb_substr($pre, 0, $i);
}
}
// Suffix
$suf = mb_substr($string, -$width);
if (mb_substr($suf, 0, 1) !== ' ' && ($i = static::indexOf($suf, ' '))) {
if ($i >= 0) {
$suf = mb_substr($suf, $i);
}
}
return trim($pre) . $glue . trim($suf);
}
return $string;
}
/**
* Checks to see if the string starts with a specific value.
*
* @param string $string
* @param string $needle
* @param bool $strict
* @return bool
*/
public static function startsWith(string $string, string $needle, bool $strict = true): bool {
$start = static::extract($string, 0, mb_strlen($needle));
if ($strict) {
return ($start === $needle);
}
return (mb_strtolower($start) === mb_strtolower($needle));
}
/**
* Truncates a string to a certain length. Will preserve HTML tags and words if the flags are true.
*
* @param string $string
* @param int $limit
* @param \Titon\Utility\OptionMap $options {
* @var bool $html True to preserve HTML tags
* @var bool $word True to preserve trailing words
* @var string $suffix Will be appended to the end of the output
* @var string $prefix Will be appended to the beginning of the out output
* @var string $open The opening tag (defaults to < HTML)
* @var string $close The closing tag (defaults to > HTML)
* }
* @return string
*/
public static function truncate(string $string, int $limit = 25, OptionMap $options = Map {}): string {
$options = (Map {
'html' => true,
'word' => true,
'suffix' => '…',
'prefix' => '',
'open' => '<',
'close' => '>'
})->setAll($options);
$open = (string) $options['open'];
$close = (string) $options['close'];
// If we should preserve HTML
if ($open !== '<' || $close !== '>') {
$options['html'] = false;
}
if (!$options['html']) {
$string = strip_tags($string);
}
// If string is shorten than limit
$length = mb_strlen($string);
if ($length <= $limit || !$limit) {
return $string;
}
// Generate tokens
$tokens = [];
$token = '';
$i = 0;
while ($i < $length) {
$char = $string[$i];
if ($char === $open || $char === '&') {
$tokens[] = $token;
$token = $char;
} else if ($char === $close || $char === ';') {
$tokens[] = $token . $char;
$token = '';
} else {
$token .= $char;
}
$i++;
}
$tokens[] = $token;
// Determine output
$current = 0;
$inHtml = false;
$htmlPattern = '/\\' . $open . '\/?(?:.*?)\\' . $close . '/iSu';
$entityPattern = '/&[a-z0-9]{2,8};|&#[0-9]{1,7};/iSu';
$output = '';
foreach ($tokens as $token) {
// Increase limit by 1 for tokens
if (preg_match($entityPattern, $token) && $current < $limit) {
$current++;
$output .= $token;
// Increase limit by 0 for HTML tags but check for tag boundaries
} else if (preg_match($htmlPattern, $token)) {
$inHtml = (mb_substr($token, 0, 2) !== $open . '/');
$output .= $token;
// Regular string
} else {
$length = mb_strlen($token);
if ($current >= $limit) {
// Do nothing, we reached the limit
} else if (($current + $length) >= $limit) {
$allowed = ($limit - $current);
$output .= mb_substr($token, 0, $allowed);
$current += $allowed;
} else {
$output .= $token;
$current += $length;
}
}
// We done?
if ($current >= $limit && !$inHtml) {
break;
}
}
// If we should preserve words
if ($options['word']) {
$lastChar = mb_substr($output, -1);
if ($lastChar !== ' ' && $lastChar !== $close && $lastChar !== ';') {
$output = mb_substr($string, 0, static::lastIndexOf($output, ' '));
}
}
return (string) $options['prefix'] . trim($output) . (string) $options['suffix'];
}
/**
* Creates UUID version 4: random number generation based.
*
* @return string
*/
public static function uuid(): string {
return sprintf('%s-%s-%s%s-%s%s-%s',
static::generate(8, self::HEX), // 1
static::generate(4, self::HEX), // 2
4, // 3
static::generate(3, self::HEX), // 3
static::generate(1, '89AB'), // 4
static::generate(3, self::HEX), // 4
static::generate(12, self::HEX)); // 5
}
}