-
Notifications
You must be signed in to change notification settings - Fork 0
/
Editor.php
1331 lines (1139 loc) · 39.4 KB
/
Editor.php
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Hipsterjazzbo\Editor;
use InvalidArgumentException;
use Hipsterjazzbo\Editor\Inflectors;
class Editor
{
/**
* @var string
*/
protected $str;
/**
* @var string
*/
protected $encoding;
/**
* @var array
*/
protected static $inflectors = [
'en' => Inflectors\En::class,
'es' => Inflectors\Es::class,
'fr' => Inflectors\Fr::class,
'nb' => Inflectors\Nb::class,
'pt' => Inflectors\Pt::class,
'tr' => Inflectors\Tr::class,
];
/**
* Editor constructor.
*
* @param string $str
* @param string $encoding
*/
public function __construct(string $str, string $encoding = 'UTF-8')
{
$this->str = $str;
$this->encoding = $encoding;
}
/**
* Create a new instance of Editor
*
* @param string $str
* @param string $encoding
*
* @return Editor
*/
public static function create(string $str, string $encoding = 'UTF-8'): self
{
return new static($str, $encoding);
}
/**
* Create a new instance of Editor from an array of strings, joined by $separator and trimmed.
*
* @param array $strs
* @param string $joinedBy
* @param string $encoding
*
* @return Editor
*/
public static function createFromArray(array $strs, string $joinedBy = ' ', string $encoding = 'UTF-8'): self
{
$strs = array_map(function ($str) use ($encoding) {
return static::create($str, $encoding)->trim();
}, $strs);
$str = implode($joinedBy, $strs);
return static::create($str, $encoding)->trim();
}
/**
* Get the encoding that's being used
*
* @return string
*/
public function getEncoding(): string
{
return $this->encoding;
}
/**
* @param string $encoding
*
* @return Editor
*/
public function setEncoding(string $encoding = 'UTF-8'): self
{
$this->encoding = $encoding;
return $this;
}
/**
* @return string
*/
public function __toString(): string
{
return $this->str();
}
/**
* @return string
*/
public function str()
{
return $this->str;
}
/////////////////////////////////////////
/// Slice and Manipulate
/////////////////////////////////////////
/**
* Get the contents of $str after $search
*
* @param string $search
*
* @return Editor
*/
public function after(string $search): self
{
if ($search === '') {
return $this;
}
$str = array_reverse(explode($search, $this->str, 2))[0];
return static::create($str);
}
/**
* Get the contents of $str before $search
*
* @param string $search
*
* @return Editor
*/
public function before(string $search): self
{
if ($search === '') {
return $this;
}
$str = explode($search, $this->str)[0];
return static::create($str);
}
/**
* Prepend $str
*
* @param string $str
* @param string $joinedBy
*
* @return $this
*/
public function prepend(string $str, string $joinedBy = ''): self
{
return new static($str.$joinedBy.$this->str);
}
/**
* Append $str
*
* @param string $str
* @param string $joinedBy
*
* @return $this
*/
public function append(string $str, string $joinedBy = ''): self
{
return new static($this->str.$joinedBy.$str);
}
/**
* Prepend $prefix to $str
*
* @param string $prefix
*
* @return Editor
*/
public function startWith(string $prefix): self
{
$quoted = preg_quote($prefix, '/');
$str = $prefix.preg_replace('/^(?:'.$quoted.')+/u', '', $this->str);
return static::create($str);
}
/**
* Append $suffix to $str
*
* @param string $suffix
*
* @return Editor
*/
public function finishWith(string $suffix): self
{
$quoted = preg_quote($suffix, '/');
$str = preg_replace('/(?:'.$quoted.')+$/u', '', $this->str).$suffix;
return static::create($str);
}
/**
* Limit the length of $str to N $characters, including $suffix
*
* @param int $characters
* @param string $suffix
*
* @return Editor
*/
public function limitCharacters(int $characters, string $suffix = '…'): self
{
if (mb_strwidth($this->str, 'UTF-8') <= $characters) {
return $this;
}
// Make sure the final string will fit within the limit even with the suffix
$trimLength = $characters - static::create($suffix)->length();
$str = rtrim(mb_strimwidth($this->str, 0, $trimLength, '', 'UTF-8')).$suffix;
return static::create($str);
}
/**
* Limit the length of $str to N $words
*
* @param int $words
* @param string $suffix
*
* @return Editor
*/
public function limitWords(int $words, string $suffix = '…'): self
{
$matches = [];
preg_match('/^\s*+(?:\S++\s*+){1,'.$words.'}/u', $this->str, $matches);
if (! isset($matches[0]) || mb_strlen($this->str) === mb_strlen($matches[0])) {
return $this;
}
$str = rtrim($matches[0]).$suffix;
return static::create($str);
}
/**
* Pluralize $str
*
* @param float $count
* @param string $language
*
* @return Editor
* @throws \Exception
*/
public function plural(float $count = 2, string $language = 'en'): self
{
if ($count == 1) {
return $this->singular($language);
}
return static::create($this->getInflector($language)->pluralize());
}
/**
* Singularize $str
*
* @param string $language
*
* @return Editor
* @throws \Exception
*/
public function singular(string $language = 'en'): self
{
return static::create($this->getInflector($language)->singularize());
}
/**
* Replace occurrences of $search with $replacement, up to $count times
*
* @param string $search
* @param string $replacement
* @param int|null $count
*
* @return Editor
*/
public function replace(string $search, string $replacement, int &$count = null): self
{
$str = str_replace($search, $replacement, $this->str, $count);
return static::create($str);
}
/**
* Replace only the first occurrence of $search with $replacement
*
* @param string $search
* @param string $replacement
*
* @return Editor
*/
public function replaceFirst(string $search, string $replacement): self
{
if ($search === '') {
return $this;
}
$start = mb_strpos($this->str, $search);
if ($start === false) {
return $this;
}
$str = $this->replaceSub($replacement, $start, static::create($search)->length());
return static::create($str);
}
/**
* Replace only the last occurrence of $search with $replacement
*
* @param string $search
* @param string $replacement
*
* @return Editor
*/
public function replaceLast(string $search, string $replacement): self
{
$start = mb_strrpos($this->str, $search);
if ($search === '' || $start === false) {
return $this;
}
$str = $this->replaceSub($replacement, $start, static::create($search)->length());
return static::create($str);
}
/**
* Replace within $str from the $start character plus $length characters
*
* @param string $replacement
* @param int $start
* @param int|null $length
*
* @return Editor
*/
public function replaceSub(string $replacement, int $start, int $length = null): self
{
preg_match_all('/./us', $this->str, $strMatches);
preg_match_all('/./us', $replacement, $replacementMatches);
if ($length === null) {
$length = $this->length();
}
array_splice($strMatches[0], $start, $length, $replacementMatches[0]);
$str = join($strMatches[0]);
return static::create($str);
}
/**
* Remove occurrences of $search, up to $count times
*
* @param string $search
* @param int|null $count
*
* @return Editor
*/
public function remove(string $search, int &$count = null): self
{
return $this->replace($search, '', $count);
}
/**
* Remove only the first occurrence of $search
*
* @param string $search
*
* @return Editor
*/
public function removeFirst(string $search): self
{
return $this->replaceFirst($search, '');
}
/**
* Remove only the last occurrence of $search
*
* @param string $search
*
* @return Editor
*/
public function removeLast(string $search): self
{
return $this->replaceLast($search, '');
}
/**
* Transform $str into a url-safe slug
*
* @param string $separator
* @param string $language
*
* @return Editor
*/
public function slug(string $separator = '-', string $language = 'en'): self
{
$str = $this->ascii($language);
// Convert all dashes/underscores into $separator
$flip = $separator === '-' ? '_' : '-';
$str = preg_replace('!['.preg_quote($flip).']+!u', $separator, $str);
// Replace @ with the word 'at'
$str = str_replace('@', $separator.'at'.$separator, $str);
// Lowercase it
$str = static::create($str)->lowerCase()->str();
// Remove all characters that are not the separator, letters, numbers, or whitespace.
$str = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', $str);
// Replace all separator characters and whitespace by a single separator
$str = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $str);
return static::create($str)->trim($separator);
}
/**
* Break $str into chunks
*
* @param int $chunkSize
*
* @return Editor[]
* @throws \Exception
*/
public function chunk(int $chunkSize = 1): array
{
if ($chunkSize <= 0) {
throw new \Exception(
'The length of each segment must be greater than zero'
);
}
$result = [];
$length = $this->length();
for ($ii = 0; $ii < $length; $ii += $chunkSize) {
$result[] = $this->slice($ii, $chunkSize);
}
if (empty($result)) {
return [static::create('')];
}
return $result;
}
/**
* Unicode safely split $str into an array of words.
*
* @see https://stackoverflow.com/a/8422356/714260
*
* @return Editor[]
*/
public function splitWords(): array
{
preg_match_all('/[\p{L}\p{M}]+/u', $this->str, $result, PREG_PATTERN_ORDER);
return array_map(function ($str) {
return static::create($str);
}, $result[0]);
}
/**
* Get the first word of $str
*
* @return Editor
*/
public function firstWord(): self
{
return static::create($this->splitWords()[0]);
}
/**
* Get the last word of $str
*
* @return Editor
*/
public function lastWord(): self
{
$words = $this->splitWords();
return static::create(end($words));
}
/**
* Slice $str from $start, with optional $length
*
* @param int $start
* @param int|null $length
*
* @return Editor
*/
public function slice(int $start, int $length = null): self
{
$str = mb_substr($this->str, $start, $length, $this->encoding);
return static::create($str);
}
/**
* Trim characters from $charList from the beginning and end of $str
*
* @param string $charList
*
* @return Editor
*/
public function trim($charList = " \t\n\r\0\x0B"): self
{
$str = trim($this->str, $charList);
return static::create($str);
}
public function ltrim($charList = " \t\n\r\0\x0B"): self
{
$str = ltrim($this->str, $charList);
return static::create($str);
}
public function rtrim($charList = " \t\n\r\0\x0B"): self
{
$str = rtrim($this->str, $charList);
return static::create($str);
}
public function base64encode(): self
{
$str = base64_encode($this->str);
return static::create($str);
}
/////////////////////////////////////////
/// Search and Query
/////////////////////////////////////////
/**
* Determine whether $str contains $search
*
* @param string $search
*
* @return bool
*/
public function contains(string $search): bool
{
return $search !== '' && mb_strpos($this->str, $search) !== false;
}
/**
* Determine whether $str starts with $search
*
* @param string $search
*
* @return bool
*/
public function startsWith(string $search): bool
{
$searchLength = static::create($search)->length();
return $search !== '' && mb_substr($this->str, 0, $searchLength) === $search;
}
/**
* Determine whether $str end with $search
*
* @param string $search
*
* @return bool
*/
public function endsWith(string $search): bool
{
$searchLength = static::create($search)->length();
return $search !== '' && mb_substr($this->str, -$searchLength) === $search;
}
/**
* Determine whether $str matches a regular expression
*
* @param string $pattern
*
* @return bool
*/
public function matches(string $pattern): bool
{
// If the given value is an exact match we can of course return true right
// from the beginning. Otherwise, we will translate asterisks and do an
// actual pattern match against the two strings to see if they match.
if ($pattern == $this->str) {
return true;
}
$pattern = preg_quote($pattern, '#');
// Asterisks are translated into zero-or-more regular expression wildcards
// to make it convenient to check if the strings starts with the given
// pattern such as "library/*", making any string check convenient.
$pattern = str_replace('\*', '.*', $pattern);
return preg_match('#^'.$pattern.'\z#u', $this->str) === 1;
}
/**
* Get length of $str
*
* @return int
*/
public function length(): int
{
return mb_strlen($this->str, $this->encoding);
}
/////////////////////////////////////////
/// Casing
/////////////////////////////////////////
/**
* Transform $str to lower case
*
* @return Editor
*/
public function lowerCase(): self
{
$str = mb_strtolower($this->str, $this->encoding);
return static::create($str);
}
/**
* Transform the first character of $str to lower case
*
* @return Editor
*/
public function lowerCaseFirst(): self
{
$str = $this->slice(0, 1)->lowerCase().$this->slice(1);
return static::create($str);
}
/**
* Transform the first character of each word of $str to lower case
*
* @param string $delimiters
*
* @return Editor
* @throws \Exception
*/
public function lowerCaseWords($delimiters = " \t\r\n\f\v")
{
$delimitersArray = static::create($delimiters)->chunk(1);
$upper = true;
$str = '';
for ($ii = 0; $ii < $this->length(); $ii++) {
$char = $this->slice($ii, 1);
if ($upper) {
$char = mb_convert_case($char, MB_CASE_LOWER, $this->encoding);
$upper = false;
} elseif (in_array($char, $delimitersArray)) {
$upper = true;
}
$str .= $char;
}
return static::create($str);
}
/**
* Transform $str ot upper case
*
* @return Editor
*/
public function upperCase(): self
{
$str = mb_strtoupper($this->str, $this->encoding);
return static::create($str);
}
/**
* Transform the first character of $str to upper case
*
* @return Editor
*/
public function upperCaseFirst(): self
{
$str = $this->slice(0, 1)->upperCase().$this->slice(1);
return static::create($str);
}
/**
* Transform the first character of each word of $str to upper case
*
* @param array $delimiters
*
* @return Editor
* @throws \Exception
*/
public function upperCaseWords($delimiters = [" ", "\t", "\r", "\n", "\f", "\v"]): self
{
$upper = true;
$str = '';
for ($ii = 0; $ii < $this->length(); $ii++) {
$char = $this->slice($ii, 1);
if ($upper) {
$char = mb_convert_case($char, MB_CASE_UPPER, $this->encoding);
$upper = false;
} elseif (in_array($char, $delimiters)) {
$upper = true;
}
$str .= $char;
}
return static::create($str);
}
/**
* Transform $str to proper title case
*
* @param array $ignore
*
* @return Editor
*/
public function titleCase(array $ignore = []): self
{
$smallWords = array_merge(
[
'(?<!q&)a',
'an',
'and',
'as',
'at(?!&t)',
'but',
'by',
'en',
'for',
'if',
'in',
'of',
'on',
'or',
'the',
'to',
'v[.]?',
'via',
'vs[.]?',
'with',
],
$ignore
);
$smallWordsRx = implode('|', $smallWords);
$apostropheRx = '(?x: [\'’] [[:lower:]]* )?';
$str = $this->trim();
if (preg_match('/[[:lower:]]/', $str) === 0) {
$str = $str->lowerCase()->str();
}
// The main substitutions
$str = preg_replace_callback(
'~\b (_*) (?: # 1. Leading underscore and
( (?<=[ ][/\\\\]) [[:alpha:]]+ [-_[:alpha:]/\\\\]+ | # 2. file path or
[-_[:alpha:]]+ [@.:] [-_[:alpha:]@.:/]+ '.$apostropheRx.' ) # URL, domain, or email
|
( (?i: '.$smallWordsRx.' ) '.$apostropheRx.' ) # 3. or small word (case-insensitive)
|
( [[:alpha:]] [[:lower:]\'’()\[\]{}]* '.$apostropheRx.' ) # 4. or word w/o internal caps
|
( [[:alpha:]] [[:alpha:]\'’()\[\]{}]* '.$apostropheRx.' ) # 5. or some other word
) (_*) \b # 6. With trailing underscore
~ux',
function ($matches) {
// Preserve leading underscore
$tmpStr = $matches[1];
if ($matches[2]) {
// Preserve URLs, domains, emails and file paths
$tmpStr .= $matches[2];
} elseif ($matches[3]) {
// Lower-case small words
$tmpStr .= static::create($matches[3])->lowerCase();
} elseif ($matches[4]) {
// Capitalize word w/o internal caps
$tmpStr .= static::create($matches[4])->upperCaseFirst();
} else {
// Preserve other kinds of word (iPhone)
$tmpStr .= $matches[5];
}
// Preserve trailing underscore
$tmpStr .= $matches[6];
return $tmpStr;
},
$str
);
// Exceptions for small words: capitalize at start of title...
$str = preg_replace_callback(
'~( \A [[:punct:]]* # start of title...
| [:.;?!][ ]+ # or of sub-sentence...
| [ ][\'"“‘(\[][ ]* ) # or of inserted sub-phrase...
( '.$smallWordsRx.' ) \b # ...followed by small word
~uxi',
function ($matches) {
return $matches[1].static::create($matches[2])->upperCaseFirst();
},
$str
);
// ...and end of title
$str = preg_replace_callback(
'~\b ( '.$smallWordsRx.' ) # small word...
(?= [[:punct:]]* \Z # ...at the end of the title...
| [\'"’”)\]] [ ] ) # ...or of an inserted sub-phrase?
~uxi',
function ($matches) {
return static::create($matches[1])->upperCaseFirst();
},
$str
);
// Exceptions for small words in hyphenated compound words
// e.g. "in-flight" -> In-Flight
$str = preg_replace_callback(
'~\b
(?<! -) # Negative lookbehind for a hyphen; we do not want to match man-in-the-middle but do want (in-flight)
( '.$smallWordsRx.' )
(?= -[[:alpha:]]+) # lookahead for "-someword"
~uxi',
function ($matches) {
return static::create($matches[1])->upperCaseFirst();
},
$str
);
// e.g. "Stand-in" -> "Stand-In" (Stand is already capped at this point)
$str = preg_replace_callback(
'~\b
(?<!…) # Negative lookbehind for a hyphen; we do not want to match man-in-the-middle but do want (stand-in)
( [[:alpha:]]+- ) # $1 = first word and hyphen, should already be properly capped
( '.$smallWordsRx.' ) # ...followed by small word
(?! - ) # Negative lookahead for another -
~uxi',
function ($matches) {
return $matches[1].static::create($matches[2])->upperCaseFirst();
},
$str
);
return static::create($str);
}
/**
* Transform $str to camelCase
*
* @return Editor
* @throws \Exception
*/
public function camelCase(): self
{
return $this->studlyCase()->lowerCaseFirst();
}
/**
* Transform $str to StudlyCase
*
* @return Editor
* @throws \Exception
*/
public function studlyCase(): self
{
return $this->replace('-', ' ')
->replace('_', ' ')
->upperCaseWords()
->remove(' ');
}
/**
* Transform $str to snake_case
*
* @param string $delimiter
*
* @return Editor
* @throws \Exception
*/
public function snakeCase(string $delimiter = '_'): self
{
$str = preg_replace('/\s+/u', '', $this->upperCaseWords());
$str = preg_replace('/(.)(?=[A-Z])/u', '$1'.$delimiter, $str);
return static::create($str)->lowerCase();
}
/**
* Transform $str to kebab-case
*
* @return Editor
* @throws \Exception
*/
public function kebabCase(): self
{
return $this->snakeCase('-');
}
/////////////////////////////////////////
/// Utilities
/////////////////////////////////////////
/**
* Transform $str to be ascii-safe
*
* @param string $languageCode
*
* @return Editor
*/
public function ascii(string $languageCode = 'en'): self
{
$str = $this;
$languageCode = static::processLanguageCode($languageCode);
$languageSpecific = static::languageSpecificCharsArray($languageCode);
if (! is_null($languageSpecific)) {
foreach ($languageSpecific as $search => $replace) {
$str = $str->replace($search, $replace);
}
}
foreach (static::charsArray() as $safeChar => $unsafeChars) {
foreach ($unsafeChars as $unsafeChar) {
$str = $str->replace($unsafeChar, $safeChar);
}
}
$str = preg_replace('/[^\x20-\x7E]/u', '', $str->str());
return static::create($str);
}
/**
* @param string $format
* @param mixed ...$substitutions
* @return \Hipsterjazzbo\Editor\Editor
*/
public static function sprintf(string $format, ...$substitutions): self
{
return static::vsprintf($format, $substitutions);
}
/**
* @param string $format