[LIB][Util] Update Common::setConfig to throw an exception if appropriate, add Formatting::{toString,toArray}

This commit is contained in:
Hugo Sales 2020-07-25 14:42:00 +00:00 committed by Hugo Sales
parent 72ee91a8da
commit 292d98a33c
2 changed files with 38 additions and 6 deletions

View File

@ -52,12 +52,17 @@ abstract class Common
/** /**
* Set sysadmin's configuration preferences for GNU social * 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]); $c = DB::getPartialReference('config', ['section' => $section, 'setting' => $setting]);
$obj->setValue(serialize($value)); if ($c === null) {
DB::persist($obj); throw new \Exception("The field section = {$section} and setting = {$setting} doesn't exist");
}
$c->setValue(serialize($value));
DB::flush(); DB::flush();
} }

View File

@ -134,8 +134,8 @@ abstract class Formatting
* Indent $in, a string or array, $level levels * Indent $in, a string or array, $level levels
* *
* @param array|string $in * @param array|string $in
* @param int $level * @param int $level How many levels of indentation
* @param int $count * @param int $count How many spaces per indentation
* *
* @return string * @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); 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;
}
} }