MDAllowedValueSets/src/MDUnitsSet.php

100 lines
2.6 KiB
PHP

<?PHP
/**
* Contains a class for controlling the list of available units.
*
* @author Joshua Ramon Enslin <joshua@museum-digital.de>
*/
declare(strict_types = 1);
/**
* Class containing available units for weights, lengths etc.
*/
final class MDUnitsSet extends MDValueSet {
const UNITS_LENGTH = ['', 'm', 'dm', 'cm', 'mm', 'ft', 'in'];
const UNITS_WEIGHT = ['', 't', 'kg', 'g'];
const UNITS_LENGTH_TO_MILLIMETER = [
'm' => 1000,
'ft' => 304.8,
'dm' => 100,
'in' => 25.4,
'cm' => 10,
'mm' => 1,
];
const UNITS_WEIGHT_TO_GRAMM = [
't' => 1000000,
'kg' => 1000,
'g' => 1,
];
/**
* Converts a given length to millimeters.
*
* @param mixed $value Input value to convert.
* @param string $unit Length unit of the value to convert.
*
* @return float|null
*/
public static function convertLengthToMillimeter(mixed $value, string $unit):float|null {
if (!isset(self::UNITS_LENGTH_TO_MILLIMETER[$unit])) return null;
try {
$number = MD_STD_IN::sanitize_float($value);
return floatval($number * self::UNITS_LENGTH_TO_MILLIMETER[$unit]);
}
catch (MDgenericInvalidInputsException $e) {
return null;
}
}
/**
* Converts a given weight to gramm.
*
* @param mixed $value Input value to convert.
* @param string $unit Weight unit of the value to convert.
*
* @return float|null
*/
public static function convertWeightToGramm(mixed $value, string $unit):float|null {
if (!isset(self::UNITS_WEIGHT_TO_GRAMM[$unit])) return null;
try {
$number = MD_STD_IN::sanitize_float($value);
return floatval($number * self::UNITS_WEIGHT_TO_GRAMM[$unit]);
}
catch (MDgenericInvalidInputsException $e) {
return null;
}
}
/**
* Returns a translated list of length units.
*
* @param MDTlLoader $tlLoader Translation loader.
*
* @return array<string>
*/
public static function getLengthUnitsTLed(MDTlLoader $tlLoader):array {
return parent::getTlUnsortedList($tlLoader, self::UNITS_LENGTH, "units_length_set", "units_length_set");
}
/**
* Returns a translated list of weight units.
*
* @param MDTlLoader $tlLoader Translation loader.
*
* @return array<string>
*/
public static function getWeightUnitsTLed(MDTlLoader $tlLoader):array {
return parent::getTlUnsortedList($tlLoader, self::UNITS_WEIGHT, "units_weight_set", "units_weight_set");
}
}