3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Core\Config\Util;
25 * Util to transform back the config array into a string
27 class ConfigFileTransformer
29 public static function encode(array $data): string
31 $dataString = '<?php' . PHP_EOL . PHP_EOL;
32 $dataString .= 'return [' . PHP_EOL;
34 $categories = array_keys($data);
36 foreach ($categories as $category) {
38 if (is_null($data[$category])) {
39 $dataString .= "\t'$category' => null," . PHP_EOL;
43 $dataString .= "\t'$category' => [" . PHP_EOL;
45 if (is_array($data[$category])) {
46 $keys = array_keys($data[$category]);
48 foreach ($keys as $key) {
49 $dataString .= static::mapConfigValue($key, $data[$category][$key]);
52 $dataString .= "\t]," . PHP_EOL;
55 $dataString .= "];" . PHP_EOL;
60 protected static function extractArray(array $config, int $level = 0): string
64 foreach ($config as $configKey => $configValue) {
65 $string .= static::mapConfigValue($configKey, $configValue, $level);
71 protected static function mapConfigValue(string $key, $value, $level = 0): string
73 $string = str_repeat("\t", $level + 2) . "'$key' => ";
75 if (is_null($value)) {
77 } elseif (is_array($value)) {
78 $string .= "[" . PHP_EOL;
79 $string .= static::extractArray($value, ++$level);
80 $string .= str_repeat("\t", $level + 1) . '],';
81 } elseif (is_bool($value)) {
82 $string .= ($value ? 'true' : 'false') . ",";
83 } elseif (is_numeric($value)) {
84 $string .= $value . ",";
86 $string .= sprintf('\'%s\',', addcslashes($value, '\'\\'));