/** * Get the conversion factor between two Units of Weight * * e.g. from LB to OZ = 16 * * @author Tom Haskins-Vaughan <*****@*****.**> * @since 0.3.0 * * @param Uom $from * @param Uom $to * * @throws ConversionNotSetException Thown when a conversion is tried * that has not been set in the conversions.json file * @throws BadConversionException Thrown when a conversion is not set * properly, e.g. [1] should be [1, 16] * @return Fraction */ public static function getConversionFactor(Uom $from, Uom $to) { // Check to see if we need to do a conversion if ($from->isSameValueAs($to)) { return new Fraction(1); } if (!isset(static::$conversions)) { static::$conversions = json_decode(utf8_encode(file_get_contents(__DIR__ . '/conversions.json')), true); } // First lets see if we have a conversion for the from to to if (isset(static::$conversions[$from->getName()][$to->getName()])) { $numeratorDenominatorPair = static::$conversions[$from->getName()][$to->getName()]; // I guess we didn't find one, try the inverse } elseif (isset(static::$conversions[$to->getName()][$from->getName()])) { // We found the inverse, set the conversion values appropriately $numeratorDenominatorPair = array_reverse(static::$conversions[$to->getName()][$from->getName()]); } else { // no conversion found. throw an exception throw new ConversionNotSetException($from->getName(), $to->getName()); } // Is the conversion set up correctly if (count($numeratorDenominatorPair) == 2) { return new Fraction($numeratorDenominatorPair[0], $numeratorDenominatorPair[1]); } else { // Guess it wasn't throw new BadConversionException(); } }