View source
<?php
namespace Drupal\physical;
final class WeightUnit implements UnitInterface {
const MILLIGRAM = 'mg';
const GRAM = 'g';
const KILOGRAM = 'kg';
const OUNCE = 'oz';
const POUND = 'lb';
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'),
];
}
public static function getBaseUnit() {
return self::KILOGRAM;
}
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];
}
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));
}
}
}