Add helper to convert between units of measurement

This commit is contained in:
Cram42 2022-11-01 19:49:57 +08:00
parent 35536b5dbd
commit 7c355cef2d

View file

@ -1126,4 +1126,43 @@ class Helper
return $settings;
}
/**
* Conversion between units of measurement
*
* @author Grant Le Roux <grant.leroux+snipe-it@gmail.com>
* @since 5.0
* @param float $value Measurement value to convert
* @param string $srcUnit Source unit of measurement
* @param string $dstUnit Destination unit of measurement
* @param int $round Round the result to decimals (Default false - No rounding)
* @return float
*/
public static function convertUnit($value, $srcUnit, $dstUnit, $round=false) {
$srcFactor = static::getUnitConversionFactor($srcUnit);
$dstFactor = static::getUnitConversionFactor($dstUnit);
$output = $value * $srcFactor / $dstFactor;
return ($round !== false) ? round($output, $round) : $output;
}
/**
* Get conversion factor from unit of measurement to mm
*
* @author Grant Le Roux <grant.leroux+snipe-it@gmail.com>
* @since 5.0
* @param string $unit Unit of measurement
* @return float
*/
public static function getUnitConversionFactor($unit) {
switch (strtolower($unit)) {
case 'mm': return 1.0;
case 'cm': return 10.0;
case 'm': return 1000.0;
case 'in': return 25.4;
case 'ft': return 12 * static::getUnitConversionFactor('in');
case 'yd': return 3 * static::getUnitConversionFactor('ft');
case 'pt': return (1/72) * static::getUnitConversionFactor('in');
default: throw new \InvalidArgumentException('Unit: \''.$unit.'\' is not supported');
}
}
}