forked from joachim-n/case-converter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCaseString.php
116 lines (100 loc) · 2.66 KB
/
CaseString.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
<?php
namespace CaseConverter;
/**
* Converts a string from one case to another.
*
* Static methods on this class take the input string, and return a
* StringAssembler object, on which the output method should be called. E.g.:
*
* @code
* $output = \CaseConverter\CaseString::camel('MyString')->snake();
* @endcode
*/
class CaseString {
/**
* Takes a camel case string.
*
* @param $string
* The string.
*
* @return \CaseConverter\StringAssembler
* A string assembler object with the string pieces set on it.
*/
public static function camel($string) {
// Convert to pascal and then use that.
$string = ucfirst($string);
return static::pascal($string);
}
/**
* Takes a pascal case string.
*
* @param $string
* The string.
*
* @return \CaseConverter\StringAssembler
* A string assembler object with the string pieces set on it.
*/
public static function pascal($string) {
// Split on both:
// - '.|Ul': lUl 1 §
// and 'l|U'.
$pieces = preg_split('@((?<=.)(?=[[:upper:]][[:lower:]])|(?<=[[:lower:]])(?=[[:upper:]]))@', $string);
return (new StringAssembler($pieces))->areTitleCase();
}
/**
* Takes a snake case string.
*
* @param $string
* The string.
*
* @return \CaseConverter\StringAssembler
* A string assembler object with the string pieces set on it.
*/
public static function snake($string) {
$pieces = explode('_', $string);
return new StringAssembler($pieces);
}
/**
* Takes a kebab case string.
*
* @param $string
* The string.
*
* @return \CaseConverter\StringAssembler
* A string assembler object with the string pieces set on it.
*/
public static function kebab($string) {
$pieces = explode('-', $string);
return new StringAssembler($pieces);
}
/**
* Takes a title case string.
*
* @param $string
* The string.
*
* @return \CaseConverter\StringAssembler
* A string assembler object with the string pieces set on it.
*/
public static function title($string) {
$pieces = explode(' ', $string);
return (new StringAssembler($pieces))->areTitleCase();
}
/**
* Takes a sentence case string.
*
* @param $string
* The string.
*
* @return \CaseConverter\StringAssembler
* A string assembler object with the string pieces set on it.
*/
public static function sentence($string) {
$pieces = explode(' ', $string);
// Put the first word into lowercase, unless it's all capitals.
if (!preg_match('@^[[:upper:]]+$@', $pieces[0])) {
$pieces[0] = lcfirst($pieces[0]);
}
return new StringAssembler($pieces);
}
}