Created
March 17, 2021 11:31
-
-
Save redbonzai/875f35728ed71a654825a3968254f044 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace CSID\IMC\Baseline\CoreBundle\Model\Traits; | |
trait RecursiveSnakeCaseToCamelCaseKeys | |
{ | |
/** | |
* Recursively iterate through an array with snake_case keys | |
* and convert those keys to camelCase. | |
* @param array $snakeCaseArray | |
* @return array | |
*/ | |
public function recursiveSnakeCaseToCamelCaseKeys(array $snakeCaseArray): array | |
{ | |
$result = []; | |
foreach ($snakeCaseArray as $key => $val) { | |
$newKey = $this->toCamelCase($key); | |
if (!is_array($val)) { | |
$result[$newKey] = $val; | |
} else { | |
$result[$newKey] = $this->recursiveSnakeCaseToCamelCaseKeys($val); | |
} | |
} | |
return $result; | |
} | |
/** | |
* Convert snake_case words to camelCase | |
* @param string $value | |
* @return string | |
*/ | |
public function toCamelCase(string $value): string | |
{ | |
$valueArray = explode('_', $value); | |
return $this->iterateSnakeCaseWordArray($valueArray); | |
} | |
/** | |
* Iterate through a word array | |
* Capitalize the first letter of every word | |
* Join each word. | |
* @param array $wordArray | |
* @return string | |
*/ | |
public function iterateSnakeCaseWordArray(array $wordArray): string | |
{ | |
$i = 0; | |
$capitalizedWords = []; | |
foreach ($wordArray as $word) { | |
$i === 0 | |
? $capitalizedWords[] = $word | |
: $capitalizedWords[] = ucwords($word); | |
$i++; | |
} | |
return implode('', $capitalizedWords); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This trait recursively converts snake_case keys to camelCase for multi-nested associative arrays.