Convert::upperCamelToLowerCamel()

Used to expose lowercase web service object keys in SS4,
without requiring an explicit field mapping for these.

The first use case is exposing File data:
[ID => 99, FileName => 'test'] becomes {"id": 99, "fileName": "test"} in JSON.
This commit is contained in:
Ingo Schommer 2016-06-23 12:27:54 +12:00
parent 27ce71390a
commit fd0c8ad4c0
2 changed files with 81 additions and 0 deletions

View File

@ -439,4 +439,47 @@ class Convert {
true
);
}
/**
* Converts upper camel case names to lower camel case,
* with leading upper case characters replaced with lower case.
* Tries to retain word case.
*
* Examples:
* - ID => id
* - IDField => idField
* - iDField => iDField
*
* @param $str
* @return string
*/
public static function upperCamelToLowerCamel($str) {
$return = null;
$matches = null;
if(preg_match('/(^[A-Z]{1,})([A-Z]{1})([a-z]+.*)/', $str, $matches)) {
// If string has trailing lowercase after more than one leading uppercase characters,
// match everything but the last leading uppercase character.
$return = implode('', [
strtolower($matches[1]),
$matches[2],
$matches[3]
]);
} else if(preg_match('/(^[A-Z]{1})([a-z]+.*)/', $str, $matches)) {
// If string has trailing lowercase after exactly one leading uppercase characters,
// match everything but the last leading uppercase character.
$return = implode('', [
strtolower($matches[1]),
$matches[2]
]);
} elseif(preg_match('/^[A-Z]+$/', $str)) {
// If string has leading uppercase without trailing lowercase,
// just lowerase the whole thing.
$return = strtolower($str);
} else {
// If string has no leading uppercase, just return.
$return = $str;
}
return $return;
}
}

View File

@ -396,4 +396,42 @@ XML
Convert::base64url_decode(Convert::base64url_encode($data))
);
}
public function testUpperCamelToLowerCamel() {
$this->assertEquals(
'd',
Convert::upperCamelToLowerCamel('D'),
'Single character'
);
$this->assertEquals(
'id',
Convert::upperCamelToLowerCamel('ID'),
'Multi leading upper without trailing lower'
);
$this->assertEquals(
'id',
Convert::upperCamelToLowerCamel('Id'),
'Single leading upper with trailing lower'
);
$this->assertEquals(
'idField',
Convert::upperCamelToLowerCamel('IdField'),
'Single leading upper with trailing upper camel'
);
$this->assertEquals(
'idField',
Convert::upperCamelToLowerCamel('IDField'),
'Multi leading upper with trailing upper camel'
);
$this->assertEquals(
'iDField',
Convert::upperCamelToLowerCamel('iDField'),
'Single leading lower with trailing upper camel'
);
$this->assertEquals(
'_IDField',
Convert::upperCamelToLowerCamel('_IDField'),
'Non-alpha leading with trailing upper camel'
);
}
}