Last active
July 22, 2023 17:52
-
-
Save a-r-m-i-n/442693801bab280e42b7 to your computer and use it in GitHub Desktop.
Method to convert array to TypoScript string
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 | |
/** | |
* Converts given array to TypoScript | |
* | |
* @param array $typoScriptArray The array to convert to string | |
* @param string $addKey Prefix given values with given key (eg. lib.whatever = {...}) | |
* @param integer $tab Internal | |
* @param boolean $init Internal | |
* @return string TypoScript | |
*/ | |
function convertArrayToTypoScript(array $typoScriptArray, $addKey = '', $tab = 0, $init = TRUE) { | |
$typoScript = ''; | |
if ($addKey !== '') { | |
$typoScript .= str_repeat("\t", ($tab === 0) ? $tab : $tab - 1) . $addKey . " {\n"; | |
if ($init === TRUE) { | |
$tab++; | |
} | |
} | |
$tab++; | |
foreach($typoScriptArray as $key => $value) { | |
if (!is_array($value)) { | |
if (strpos($value, "\n") === FALSE) { | |
$typoScript .= str_repeat("\t", ($tab === 0) ? $tab : $tab - 1) . "$key = $value\n"; | |
} else { | |
$typoScript .= str_repeat("\t", ($tab === 0) ? $tab : $tab - 1) . "$key (\n$value\n" . str_repeat("\t", ($tab === 0) ? $tab : $tab - 1) . ")\n"; | |
} | |
} else { | |
$typoScript .= $this->convertArrayToTypoScript($value, $key, $tab, FALSE); | |
} | |
} | |
if ($addKey !== '') { | |
$tab--; | |
$typoScript .= str_repeat("\t", ($tab === 0) ? $tab : $tab - 1) . '}'; | |
if ($init !== TRUE) { | |
$typoScript .= "\n"; | |
} | |
} | |
return $typoScript; | |
} |
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 | |
// Example array | |
$array = array( | |
'name' => 'Armin', | |
'firstName' => 'Vieweg', | |
'description' => 'He is a' . PHP_EOL . 'TYPO3 and PHP developer', | |
'skills' => array( | |
'php' => 'yep', | |
'typo3' => 'also yep' | |
) | |
); | |
$typoScript = convertArrayToTypoScript($array, 'lib.developer.armin'); | |
file_put_contents('example.ts', $typoScript); |
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
# This is the output of example.ts: | |
lib.developer.armin { | |
name = Armin | |
firstName = Vieweg | |
description ( | |
He is a | |
TYPO3 and PHP developer | |
) | |
skills { | |
php = yep | |
typo3 = also yep | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment