Config: expose APIs to parse/emit list configs

This commit is contained in:
Dylan K. Taylor 2021-10-07 21:18:42 +01:00
parent 2a3a57c519
commit d5f02a0bf8
No known key found for this signature in database
GPG Key ID: 8927471A91CAFD3D

View File

@ -183,7 +183,7 @@ class Config{
$config = unserialize($content); $config = unserialize($content);
break; break;
case Config::ENUM: case Config::ENUM:
$config = self::parseList($content); $config = array_fill_keys(self::parseList($content), true);
break; break;
default: default:
throw new \InvalidStateException("Config type is unknown"); throw new \InvalidStateException("Config type is unknown");
@ -223,7 +223,7 @@ class Config{
$content = serialize($this->config); $content = serialize($this->config);
break; break;
case Config::ENUM: case Config::ENUM:
$content = implode("\r\n", array_keys($this->config)); $content = self::writeList(array_keys($this->config));
break; break;
default: default:
throw new \InvalidStateException("Config type is unknown, has not been set or not detected"); throw new \InvalidStateException("Config type is unknown, has not been set or not detected");
@ -509,21 +509,29 @@ class Config{
} }
/** /**
* @return true[] * @return string[]
* @phpstan-return array<string, true> * @phpstan-return list<string>
*/ */
private static function parseList(string $content) : array{ public static function parseList(string $content) : array{
$result = []; $result = [];
foreach(explode("\n", trim(str_replace("\r\n", "\n", $content))) as $v){ foreach(explode("\n", trim(str_replace("\r\n", "\n", $content))) as $v){
$v = trim($v); $v = trim($v);
if($v == ""){ if($v === ""){
continue; continue;
} }
$result[$v] = true; $result[] = $v;
} }
return $result; return $result;
} }
/**
* @param string[] $entries
* @phpstan-param list<string> $entries
*/
public static function writeList(array $entries) : string{
return implode("\n", array_keys($entries));
}
/** /**
* @param string[]|int[]|float[]|bool[] $config * @param string[]|int[]|float[]|bool[] $config
* @phpstan-param array<string, string|int|float|bool> $config * @phpstan-param array<string, string|int|float|bool> $config