ldc-boutique-cnc/app/Enums/WeightUnit.php
Jérémy Munsch f99e259bd5
Tons of fixes Refonte SYNC 1
- Authentification System OK
2022-11-16 12:47:41 +01:00

104 lines
2.5 KiB
PHP

<?php
namespace App\Enums;
use Kwaadpepper\Enum\BaseEnum;
/**
* @method static self g()
* @method static self kg()
* @method static self ton()
*/
final class WeightUnit extends BaseEnum
{
/**
* Enum values
*
* @return array
*/
protected static function values(): array
{
return [
'g' => 'G',
'kg' => 'KG',
'ton' => 'T',
];
}
/**
* Enum labels
*
* @return array
*/
protected static function labels(): array
{
return [
'g' => __('g'),
'kg' => __('kg'),
'ton' => __('t'),
];
}
/**
* Enum conversions a partir de gramme
*
* @return array
*/
protected static function conversions(): array
{
return [
'g' => 1,
'kg' => 1000,
'ton' => 1000000,
];
}
/**
* @param string $attribute
* @return integer|string
*/
public function __get(string $attribute)
{
if ($attribute === 'conversion') {
return $this->conversions()[$this->getDefinition()] ?? null;
}
return parent::__get($attribute);
}
/**
* Format weight into a displayable unit.
* @param integer $weightG The weight in grams.
* @param \App\Enums\WeightUnit|null $forceUnit To force specific unit display.
* @return string
*/
public static function getDisplayableWeight(int $weightG, self $forceUnit = null): string
{
if ($forceUnit) {
number_format(round($weightG / $forceUnit->conversion, 2), 2, ',', '') . $forceUnit->label;
}
$displayable = self::convertWeightToAdequatUnit($weightG);
return \number_format($displayable->value, 2, ',', '') . ' ' . $displayable->enum->label;
}
/**
* Convert value to the adequat unit
* @param integer $weightG The weight in grams.
* @return object<'enum'|'value',self>
*/
private function convertWeightToAdequatUnit(int $weightG): object
{
foreach (self::conversions() as $key => $conversionRate) {
$convertedTest = round($weightG / $conversionRate, 2);
if ($convertedTest > 0.001 and $convertedTest <= 1000) {
return (object)[
'enum' => self::make($key),
'value' => $convertedTest
];
}
}
return (object)[
'enum' => \collect(self::toArray())->last(),
'value' => $weightG
];
}
}