Files
2026-11-30 06:56:14 +02:00

123 lines
3.1 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Domain\ValueObjects;
use App\Modules\TimeTracking\Domain\Exceptions\InvalidWorkedHours;
/**
* Hours worked on one day, 0.25–24 to the nearest quarter of an hour.
* Stored as quarters so sums stay exact.
*/
final readonly class WorkedHours
{
public const int MAX_QUARTERS = 96;
public int $quarters;
public function __construct(int $quarters)
{
if ($quarters < 1 || $quarters > self::MAX_QUARTERS) {
throw new InvalidWorkedHours;
}
$this->quarters = $quarters;
}
/**
* Parses "2,5", "2.5" or "2"; null for an empty value.
*
* @throws InvalidWorkedHours
*/
public static function parse(string $value): ?self
{
$value = str_replace(',', '.', trim($value));
if ($value === '') {
return null;
}
if (! is_numeric($value)) {
throw new InvalidWorkedHours;
}
$quarters = (float) $value * 4;
if (abs($quarters - round($quarters)) > 1e-9) {
throw new InvalidWorkedHours;
}
return new self((int) round($quarters));
}
/**
* Parses what the time sheet's cell accepts (docs/ui-timesheet.md 5.1):
* "1:30" (hours and minutes), "1,5" or "1.5" (hours), a whole number up
* to 24 as hours ("2") and above it as minutes ("90"). Null for an empty
* value or zero. Always whole quarter hours.
*
* @throws InvalidWorkedHours
*/
public static function parseFlexible(string $value): ?self
{
$value = trim($value);
if ($value === '' || preg_match('/^0+([:.,]0+)?$/', $value) === 1) {
return null;
}
if (preg_match('/^(\d{1,2}):([0-5]\d)$/', $value, $matches) === 1) {
$minutes = (int) $matches[1] * 60 + (int) $matches[2];
} elseif (preg_match('/^\d+$/', $value) === 1 && (int) $value > 24) {
$minutes = (int) $value;
} else {
return self::parse($value);
}
if ($minutes % 15 !== 0) {
throw new InvalidWorkedHours;
}
return new self(intdiv($minutes, 15));
}
/**
* Hours and minutes, "1:30" or "0:00".
*/
public static function formatClock(int $quarters): string
{
$minutes = $quarters * 15;
return intdiv($minutes, 60).':'.str_pad((string) ($minutes % 60), 2, '0', STR_PAD_LEFT);
}
public static function fromDecimal(float $hours): self
{
return new self((int) round($hours * 4));
}
public function decimal(): float
{
return $this->quarters / 4;
}
public function plus(self $other): self
{
return new self($this->quarters + $other->quarters);
}
/**
* Finnish notation without trailing zeros, e.g. "7,5" or "8".
*/
public function format(): string
{
return self::formatQuarters($this->quarters);
}
public static function formatQuarters(int $quarters): string
{
return str_replace('.', ',', rtrim(rtrim(number_format($quarters / 4, 2, '.', ''), '0'), '.'));
}
}