Files
Toiminnanohjaus/app/Modules/Machines/Domain/ValueObjects/Reading.php
T

35 lines
849 B
PHP

<?php
declare(strict_types=1);
namespace App\Modules\Machines\Domain\ValueObjects;
use App\Modules\Machines\Domain\Exceptions\InvalidReading;
/**
* A counter reading or a counter amount in thousandths of the counter's
* unit, typed as "20000", "20 000" or "12,5".
*/
final class Reading
{
/**
* @return int|null Null for an empty value.
*
* @throws InvalidReading
*/
public static function parse(string $value): ?int
{
$value = str_replace(',', '.', preg_replace('/[\s\x{00A0}\x{202F}]+/u', '', $value) ?? '');
if ($value === '') {
return null;
}
if (preg_match('/^(\d{1,12})(?:\.(\d{1,3}))?$/', $value, $matches) !== 1) {
throw new InvalidReading;
}
return (int) $matches[1] * 1000 + (int) str_pad($matches[2] ?? '', 3, '0');
}
}