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'), '.')); } }