You are here

final class WeightUnit in Physical Fields 8

Provides weight units.

Hierarchy

Expanded class hierarchy of WeightUnit

File

src/WeightUnit.php, line 8

Namespace

Drupal\physical
View source
final class WeightUnit implements UnitInterface {
  const MILLIGRAM = 'mg';
  const GRAM = 'g';
  const KILOGRAM = 'kg';
  const OUNCE = 'oz';
  const POUND = 'lb';

  /**
   * {@inheritdoc}
   */
  public static function getLabels() {
    return [
      self::MILLIGRAM => t('mg'),
      self::GRAM => t('g'),
      self::KILOGRAM => t('kg'),
      self::OUNCE => t('oz'),
      self::POUND => t('lb'),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function getBaseUnit() {
    return self::KILOGRAM;
  }

  /**
   * {@inheritdoc}
   */
  public static function getBaseFactor($unit) {
    self::assertExists($unit);
    $factors = [
      self::MILLIGRAM => '0.000001',
      self::GRAM => '0.001',
      self::KILOGRAM => '1',
      self::OUNCE => '0.028349523125',
      self::POUND => '0.45359237',
    ];
    return $factors[$unit];
  }

  /**
   * {@inheritdoc}
   */
  public static function assertExists($unit) {
    $allowed_units = [
      self::MILLIGRAM,
      self::GRAM,
      self::KILOGRAM,
      self::OUNCE,
      self::POUND,
    ];
    if (!in_array($unit, $allowed_units)) {
      throw new \InvalidArgumentException(sprintf('Invalid weight unit "%s" provided.', $unit));
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
WeightUnit::assertExists public static function Asserts that the given unit exists. Overrides UnitInterface::assertExists
WeightUnit::getBaseFactor public static function Gets the base factor for the given unit. Overrides UnitInterface::getBaseFactor
WeightUnit::getBaseUnit public static function Gets the base unit. Overrides UnitInterface::getBaseUnit
WeightUnit::getLabels public static function Gets the labels for the defined units. Overrides UnitInterface::getLabels
WeightUnit::GRAM constant
WeightUnit::KILOGRAM constant
WeightUnit::MILLIGRAM constant
WeightUnit::OUNCE constant
WeightUnit::POUND constant