93 lines
2.4 KiB
PHP
93 lines
2.4 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Modules\Inventory\Domain\ValueObjects;
|
|
|
|
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
|
|
|
|
/**
|
|
* A quantity of stock in thousandths of the item's unit (e.g. 2,5 m² =
|
|
* 2500), so three decimals are kept exactly. Typed in as "2,5", "2.5" or
|
|
* "1 200".
|
|
*/
|
|
final readonly class StockQuantity
|
|
{
|
|
public const int MAX_MILLI = 9_999_999_999;
|
|
|
|
private function __construct(public int $milli) {}
|
|
|
|
/**
|
|
* @throws InvalidStockQuantity
|
|
*/
|
|
public static function ofMilli(int $milli): self
|
|
{
|
|
if (abs($milli) > self::MAX_MILLI) {
|
|
throw new InvalidStockQuantity;
|
|
}
|
|
|
|
return new self($milli);
|
|
}
|
|
|
|
/**
|
|
* A quantity greater than zero, as typed in.
|
|
*
|
|
* @throws InvalidStockQuantity
|
|
*/
|
|
public static function parsePositive(string $value): self
|
|
{
|
|
$quantity = self::parse($value);
|
|
|
|
if ($quantity === null || $quantity->milli <= 0) {
|
|
throw new InvalidStockQuantity;
|
|
}
|
|
|
|
return $quantity;
|
|
}
|
|
|
|
/**
|
|
* A quantity of zero or more as typed in, or null for an empty value.
|
|
*
|
|
* @throws InvalidStockQuantity
|
|
*/
|
|
public static function parse(string $value): ?self
|
|
{
|
|
$value = preg_replace('/[\s\x{00A0}\x{202F}]+/u', '', $value) ?? '';
|
|
$value = str_replace(',', '.', $value);
|
|
|
|
if ($value === '') {
|
|
return null;
|
|
}
|
|
|
|
if (preg_match('/^(\d{1,7})(?:\.(\d{1,3}))?$/', $value, $matches) !== 1) {
|
|
throw new InvalidStockQuantity;
|
|
}
|
|
|
|
return new self((int) $matches[1] * 1000 + (int) str_pad($matches[2] ?? '', 3, '0'));
|
|
}
|
|
|
|
public function negated(): self
|
|
{
|
|
return new self(-$this->milli);
|
|
}
|
|
|
|
/**
|
|
* Finnish format without trailing zeros: "2,5", "-1", "1 200".
|
|
*/
|
|
public static function format(int $milli): string
|
|
{
|
|
$whole = intdiv(abs($milli), 1000);
|
|
$fraction = rtrim(str_pad((string) (abs($milli) % 1000), 3, '0', STR_PAD_LEFT), '0');
|
|
|
|
return ($milli < 0 ? '-' : '').number_format($whole, 0, ',', "\u{00A0}").($fraction === '' ? '' : ','.$fraction);
|
|
}
|
|
|
|
/**
|
|
* The value for an input field: "2,5" without thousands separators.
|
|
*/
|
|
public static function inputValue(int $milli): string
|
|
{
|
|
return str_replace("\u{00A0}", '', self::format($milli));
|
|
}
|
|
}
|