From 292d98a33cfe0211a8dc2d0f2bbaf01e62f5eb4f Mon Sep 17 00:00:00 2001 From: Hugo Sales Date: Sat, 25 Jul 2020 14:42:00 +0000 Subject: [PATCH] [LIB][Util] Update Common::setConfig to throw an exception if appropriate, add Formatting::{toString,toArray} --- src/Util/Common.php | 13 +++++++++---- src/Util/Formatting.php | 31 +++++++++++++++++++++++++++++-- 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/src/Util/Common.php b/src/Util/Common.php index 94474e98b8..f0f4d04c9f 100644 --- a/src/Util/Common.php +++ b/src/Util/Common.php @@ -52,12 +52,17 @@ abstract class Common /** * Set sysadmin's configuration preferences for GNU social + * + * @param mixed $value */ - public static function setConfig(string $section, string $setting, mixed $value): void + public static function setConfig(string $section, string $setting, $value): void { - $ojb = DB::getPartialReference('config', ['section' => $section, 'setting' => $setting]); - $obj->setValue(serialize($value)); - DB::persist($obj); + $c = DB::getPartialReference('config', ['section' => $section, 'setting' => $setting]); + if ($c === null) { + throw new \Exception("The field section = {$section} and setting = {$setting} doesn't exist"); + } + + $c->setValue(serialize($value)); DB::flush(); } diff --git a/src/Util/Formatting.php b/src/Util/Formatting.php index a650e0e446..60ad300ed2 100644 --- a/src/Util/Formatting.php +++ b/src/Util/Formatting.php @@ -134,8 +134,8 @@ abstract class Formatting * Indent $in, a string or array, $level levels * * @param array|string $in - * @param int $level - * @param int $count + * @param int $level How many levels of indentation + * @param int $count How many spaces per indentation * * @return string */ @@ -155,4 +155,31 @@ abstract class Formatting } throw new InvalidArgumentException('Formatting::indent\'s first parameter must be either an array or a string. Input was: ' . $in); } + + /** + * Convert scalars, objects implementing __toString or arrays to strings + * + * @param mixed $value + */ + public static function toString($value): string + { + return is_array($value) + ? '[' . implode(', ', F\map($value, function ($s) { return "'{$s}'"; })) . ']' + : (string) $value; + } + + /** + * Convert a user supplied string to array and return whether the conversion was successfull + * + * @param mixed $output + */ + public static function toArray(string $input, &$output): bool + { + $matches = []; + if (preg_match('/^ *\[([^,]+(, ?[^,]+)*)\] *$/', $input, $matches)) { + $output = str_replace([' \'', '\'', ' "', '"'], '', explode(',', $matches[1])); + return true; + } + return false; + } }