Esempio n. 1
0
 /**
  * Create Quantity from a string, e.g.
  *
  *     * 1 LB
  *     * 0.5 KG
  *     * 1/2 OZ
  *
  * @author Tom Haskins-Vaughan <*****@*****.**>
  * @since  0.12.0
  *
  * @param string $string
  *
  * @return mixed
  */
 public static function fromString($string)
 {
     // trim white space
     $string = trim($string);
     // look for the first Uom at the end of the string
     foreach (Uom::getUoms() as $uomGroup) {
         foreach ($uomGroup as $uomName => $description) {
             $expectedPostion = strlen($string) - strlen($uomName);
             $actualPosition = strpos($string, $uomName);
             if ($expectedPostion === $actualPosition) {
                 // ok, we've found a Uom, remove it, leaving the amount
                 $amountAsString = trim(str_replace($uomName, '', $string));
                 // now see if the rest is a fraction
                 try {
                     return new static(Fraction::fromString($amountAsString), new Uom($uomName));
                 } catch (InvalidArgumentException $e) {
                 }
                 // no, so see if it is float
                 return new static(Fraction::fromFloat($amountAsString), new Uom($uomName));
             }
         }
     }
     throw new InvalidArgumentException(sprintf('Cannot parse "%s" as a %s', $string, get_called_class()));
 }