Skip to content

Commit cd606d7

Browse files
committed
Ensure mb formatString is congruent to standard ucwords() functionality
1 parent 905c32c commit cd606d7

File tree

2 files changed

+37
-3
lines changed

2 files changed

+37
-3
lines changed

src/Geocoder/Result/AbstractResult.php

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,27 @@ public function offsetUnset($offset)
6060
*/
6161
protected function formatString($str)
6262
{
63-
if (function_exists('mb_convert_case')) {
63+
if (extension_loaded('mbstring')) {
64+
$originalStr = $str;
6465
$str = mb_convert_case($str, MB_CASE_TITLE, 'UTF-8');
66+
67+
// Correct for MB_TITLE_CASE's insistence on uppercasing letters
68+
// immediately preceded by numerals, eg: 1st -> 1St
69+
$originalEncoding = mb_regex_encoding();
70+
mb_regex_encoding('UTF-8');
71+
72+
// matches an upper case letter character immediately preceded by a numeral
73+
mb_ereg_search_init($str, '[0-9]\p{Lu}');
74+
75+
while($match = mb_ereg_search_pos()) {
76+
$charPos = $match[0] + 1;
77+
// Only swap it back to lowercase if it was lowercase to begin with
78+
if (mb_ereg_match('\p{Ll}', $originalStr[$charPos])) {
79+
$str[$charPos] = mb_strtolower($str[$charPos]);
80+
}
81+
}
82+
83+
mb_regex_encoding($originalEncoding);
6584
} else {
6685
$str = $this->lowerize($str);
6786
$str = ucwords($str);
@@ -82,7 +101,7 @@ protected function formatString($str)
82101
*/
83102
protected function lowerize($str)
84103
{
85-
return function_exists('mb_strtolower') ? mb_strtolower($str, 'UTF-8') : strtolower($str);
104+
return extension_loaded('mbstring') ? mb_strtolower($str, 'UTF-8') : strtolower($str);
86105
}
87106

88107
/**
@@ -94,6 +113,6 @@ protected function lowerize($str)
94113
*/
95114
protected function upperize($str)
96115
{
97-
return function_exists('mb_strtoupper') ? mb_strtoupper($str, 'UTF-8') : strtoupper($str);
116+
return extension_loaded('mbstring') ? mb_strtoupper($str, 'UTF-8') : strtoupper($str);
98117
}
99118
}

tests/Geocoder/Tests/Result/GeocodedTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,4 +269,19 @@ public function testUpperizeViaReflection()
269269

270270
$this->assertEquals('FOO', $method->invoke($this->geocoded, 'foo'));
271271
}
272+
273+
public function testResultFormattingWithLeadingNumeral()
274+
{
275+
if (version_compare(phpversion(), '5.5.16', '<')) {
276+
$this->markTestSkipped("Character property matching for mb_ereg doesn't work for PHP < 5.5");
277+
}
278+
// MB_TITLE_CASE Will turn this into 1St so let's test to ensure we are correcting that
279+
// We do not want to "correct" 5C, however, as it is part of the original string
280+
$array = array(
281+
'streetName' => '1st ave 1A',
282+
);
283+
284+
$this->geocoded->fromArray($array);
285+
$this->assertEquals('1st Ave 1A', $this->geocoded->getStreetName());
286+
}
272287
}

0 commit comments

Comments
 (0)