syokuhou/src/GetValuesTrait.php
2023-10-20 21:21:17 +00:00

97 lines
3 KiB
PHP

<?php
// GetValuesTrait.php
// Created: 2023-10-20
// Updated: 2023-10-20
namespace Syokuhou;
use InvalidArgumentException;
/**
* Provides implementation for {@see IConfig::getValues} based on {@see IConfig::getValueInfos}.
*/
trait GetValuesTrait {
/**
* Format described in {@see IConfig::getValues}.
*
* @param array<string|string[]> $specs
* @return array<string, mixed>
*/
public function getValues(array $specs): array {
$names = [];
$evald = [];
foreach($specs as $key => $spec) {
if(is_string($spec)) {
$name = $spec;
$default = null;
$alias = null;
} elseif(is_array($spec) && !empty($spec)) {
$name = $spec[0];
$default = $spec[1] ?? null;
$alias = $spec[2] ?? null;
} else
throw new InvalidArgumentException('$specs array contains an invalid entry.');
$nameLength = strlen($name);
if($nameLength > 3 && ($colon = strrpos($name, ':')) === $nameLength - 2) {
$type = substr($name, $colon + 1, 1);
$name = substr($name, 0, $colon);
} else $type = '';
$names[] = $name;
$evald[$key] = [
'name' => $name,
'type' => $type,
'default' => $default,
'alias' => $alias,
];
}
$infos = $this->getValueInfos($names);
$results = [];
foreach($evald as $spec) {
foreach($infos as $infoTest)
if($infoTest->getName() === $spec['name']) {
$info = $infoTest;
break;
}
$resultName = $spec['alias'] ?? $spec['name'];
if(!isset($info)) {
$defaultValue = $spec['default'] ?? null;
if($spec['type'] !== '')
settype($defaultValue, match($spec['type']) {
's' => 'string',
'a' => 'array',
'i' => 'int',
'b' => 'bool',
'f' => 'float',
'd' => 'double',
default => throw new InvalidArgumentException(sprintf('Invalid type letter encountered: "%s"', $spec['type'])),
});
$results[$resultName] = $defaultValue;
continue;
}
$results[$resultName] = match($spec['type']) {
's' => $info->getString(),
'a' => $info->getArray(),
'i' => $info->getInteger(),
'b' => $info->getBoolean(),
'f' => $info->getFloat(),
'd' => $info->getFloat(),
'' => $info->getValue(),
default => throw new InvalidArgumentException('Unknown type encountered in $specs.'),
};
unset($info);
}
return $results;
}
}