時間計算スクリプト in PHP
稼働時間の計算に使う
code:php
<?php
class HM implements \Stringable {
public function __construct(
private int $h,
private int $m,
) {}
public static function new(int $h, int $m): self
{
return new self($h, $m);
}
public function toMin(): int
{
return $this->h * 60 + $this->m;
}
public function __toString(): string
{
return "{$this->h} h {$this->m} min";
}
}
class Calculator {
public function __construct(
private array $times,
) {}
public function calculate(): HM
{
$minutes = array_sum(array_map(fn (HM $hm) => $hm->toMin(), $this->times));
return HM::new($minutes / 60, $minutes % 60);
}
}
$times = [
HM::new(2, 30),
HM::new(4, 45),
HM::new(0, 45),
HM::new(1, 0),
];
$calculator = new Calculator($times);
$result = $calculator->calculate();
echo (string)$result;