-
Notifications
You must be signed in to change notification settings - Fork 0
/
CamelCaseFormatter.php
92 lines (79 loc) · 2.37 KB
/
CamelCaseFormatter.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
<?php
namespace Kolyunya\StringProcessor\Format;
use Kolyunya\StringProcessor\Format\CaseSwitcher;
use Kolyunya\StringProcessor\ProcessorInterface;
/**
* Converts a string to a "CamelCase".
* @author Kolyunya
*/
class CamelCaseFormatter extends CaseSwitcher implements ProcessorInterface
{
/**
* @inheritdoc
*/
protected $destinationCase = self::CAMEL_CASE;
/**
* @inheritdoc
*/
protected function processSnakeCase($string)
{
// Shift letters after underscores and
// the first letter to the upper case.
$pattern = '/(?<=^|_)\p{L}/u';
$callback = function ($matches) {
$match = $matches[0];
$replace = mb_convert_case($match, MB_CASE_UPPER);
return $replace;
};
$string = preg_replace_callback($pattern, $callback, $string);
// Remove all underscores.
$string = str_replace('_', '', $string);
return $string;
}
/**
* @inheritdoc
*/
protected function processKebabCase($string)
{
// Shift letters after hyphens and
// the first letter to the upper case.
$pattern = '/(?<=^|-)\p{L}/u';
$callback = function ($matches) {
$match = $matches[0];
$replace = mb_convert_case($match, MB_CASE_UPPER);
return $replace;
};
$string = preg_replace_callback($pattern, $callback, $string);
// Remove all hyphens.
$string = str_replace('-', '', $string);
return $string;
}
/**
* @inheritdoc
*/
protected function processSentenceCase($string)
{
// Shift letters after spaces and
// the first letter to the upper case.
$pattern = '/(?<=^| )\p{L}/u';
$callback = function ($matches) {
$match = $matches[0];
$replace = mb_convert_case($match, MB_CASE_UPPER);
return $replace;
};
$string = preg_replace_callback($pattern, $callback, $string);
// Remove all spaces.
$string = str_replace(' ', '', $string);
return $string;
}
/**
* @inheritdoc
*/
protected function processUndefinedCase($string)
{
$string = $this->processSnakeCase($string);
$string = $this->processKebabCase($string);
$string = $this->processSentenceCase($string);
return $string;
}
}