Skip to content

A free open source IT asset/license management system

Add helper to convert between units of measurement

Cram427c355cef2d3a
diff --git a/app/Helpers/Helper.php b/app/Helpers/Helper.php
index cfb0aa9f15..e3e8fd75c2 100644
--- a/app/Helpers/Helper.php
+++ b/app/Helpers/Helper.php
@@ -1126,4 +1126,43 @@ class Helper
return $settings;
}
+ /**
+ * Conversion between units of measurement
+ *
+ * @author Grant Le Roux <[email protected]>
+ * @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 <[email protected]>
+ * @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');
+ }
+ }
+
}