|
4 | 4 |
|
5 | 5 | class Initials
|
6 | 6 | {
|
7 |
| - private $length = 2; |
8 |
| - private $initials = 'JD'; |
9 |
| - private $keepCase = false; |
10 |
| - private $name = 'John Doe'; |
| 7 | + protected $length = 2; |
| 8 | + protected $initials = 'JD'; |
| 9 | + protected $keepCase = false; |
| 10 | + protected $allowSpecialCharacters = true; |
| 11 | + protected $name = 'John Doe'; |
11 | 12 |
|
12 | 13 | /**
|
13 | 14 | * Set the name used for generating initials.
|
@@ -38,6 +39,20 @@ public function keepCase($keepCase = true)
|
38 | 39 | return $this;
|
39 | 40 | }
|
40 | 41 |
|
| 42 | + /** |
| 43 | + * Set if should allow (or remove) special characters. |
| 44 | + * |
| 45 | + * @param boolean $allowSpecialCharacters |
| 46 | + * |
| 47 | + * @return Initials |
| 48 | + */ |
| 49 | + public function allowSpecialCharacters($allowSpecialCharacters = true) |
| 50 | + { |
| 51 | + $this->allowSpecialCharacters = $allowSpecialCharacters; |
| 52 | + |
| 53 | + return $this; |
| 54 | + } |
| 55 | + |
41 | 56 | /**
|
42 | 57 | * Set the length of the generated initials.
|
43 | 58 | *
|
@@ -113,15 +128,32 @@ public function __toString()
|
113 | 128 | *
|
114 | 129 | * @return string
|
115 | 130 | */
|
116 |
| - private function generateInitials() |
| 131 | + protected function generateInitials() |
117 | 132 | {
|
118 | 133 | $nameOrInitials = trim($this->name);
|
119 | 134 |
|
120 | 135 | if( !$this->keepCase ) {
|
121 | 136 | $nameOrInitials = mb_strtoupper($nameOrInitials);
|
122 | 137 | }
|
123 | 138 |
|
| 139 | + if( !$this->allowSpecialCharacters ) { |
| 140 | + $nameOrInitials = preg_replace('/[!@#$%^&*(),.?":{}|<>_]/', '', $nameOrInitials); |
| 141 | + } |
| 142 | + |
| 143 | + $nameOrInitials = trim( trim( $nameOrInitials, '-' ) ); |
| 144 | + |
124 | 145 | $names = explode(' ', $nameOrInitials);
|
| 146 | + |
| 147 | + // Get names with dash (-) between into separate names |
| 148 | + $names = array_map( static function ($namePart) { return explode('-', $namePart); }, $names ); |
| 149 | + $realNames = []; |
| 150 | + |
| 151 | + foreach( new \RecursiveIteratorIterator( new \RecursiveArrayIterator($names) ) as $namePart ) { |
| 152 | + $realNames[] = $namePart; |
| 153 | + } |
| 154 | + |
| 155 | + $names = $realNames; |
| 156 | + |
125 | 157 | $initials = $nameOrInitials;
|
126 | 158 | $assignedNames = 0;
|
127 | 159 |
|
@@ -159,7 +191,7 @@ private function generateInitials()
|
159 | 191 | *
|
160 | 192 | * @return string
|
161 | 193 | */
|
162 |
| - private function convertToUrlFriendlyString($string) |
| 194 | + protected function convertToUrlFriendlyString($string) |
163 | 195 | {
|
164 | 196 | foreach (static::charsArray() as $key => $val) {
|
165 | 197 | $string = str_replace($val, mb_substr($key, 0, 1), $string);
|
|
0 commit comments