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) {
37 if (is_null($data[$category])) {
38 $dataString .= "\t'$category' => null," . PHP_EOL;
42 $dataString .= "\t'$category' => [" . PHP_EOL;
44 if (is_array($data[$category])) {
45 $keys = array_keys($data[$category]);
47 foreach ($keys as $key) {
48 $dataString .= static::mapConfigValue($key, $data[$category][$key]);
51 $dataString .= "\t]," . PHP_EOL;
54 $dataString .= "];" . PHP_EOL;
59 protected static function extractArray(array $config, int $level = 0): string
63 foreach ($config as $configKey => $configValue) {
64 $string .= static::mapConfigValue($configKey, $configValue, $level);
70 protected static function mapConfigValue(string $key, $value, $level = 0): string
72 $string = str_repeat("\t", $level + 2) . "'$key' => ";
74 if (is_null($value)) {
76 } elseif (is_array($value)) {
77 $string .= "[" . PHP_EOL;
78 $string .= static::extractArray($value, ++$level);
79 $string .= str_repeat("\t", $level + 1) . '],';
80 } elseif (is_bool($value)) {
81 $string .= ($value ? 'true' : 'false') . ",";
82 } elseif (is_numeric($value)) {
83 $string .= $value . ",";
85 $string .= sprintf('\'%s\',', addcslashes($value, '\'\\'));