You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.9 KiB

2 days ago
<?php
namespace App\Console\Commands;
use Illuminate\Support\Carbon;
use InvalidArgumentException;
trait PeopleCountingDateRange
{
/**
* @return list<Carbon>
*/
protected function peopleCountingDays(?string $date, ?string $from, ?string $to, Carbon $default): array
{
$date = is_string($date) ? trim($date) : '';
$from = is_string($from) ? trim($from) : '';
$to = is_string($to) ? trim($to) : '';
if ($date !== '') {
return [$this->parsePeopleCountingDay($date)];
}
if ($from !== '' || $to !== '') {
if ($from === '') {
throw new InvalidArgumentException('指定 --to 时必须同时提供 --from');
}
$start = $this->parsePeopleCountingDay($from);
$end = $to !== '' ? $this->parsePeopleCountingDay($to) : $default->copy()->startOfDay();
if ($start->gt($end)) {
throw new InvalidArgumentException('--from 不能晚于 --to');
}
$days = [];
for ($d = $start->copy(); $d->lte($end); $d->addDay()) {
$days[] = $d->copy();
}
return $days;
}
return [$default->copy()->startOfDay()];
}
protected function parsePeopleCountingDay(string $raw): Carbon
{
try {
$dt = Carbon::createFromFormat('Y-m-d', $raw);
} catch (\Throwable $e) {
throw new InvalidArgumentException("日期须为 Y-m-d收到: {$raw}");
}
if ($dt === false || $dt->format('Y-m-d') !== $raw) {
throw new InvalidArgumentException("日期须为 Y-m-d收到: {$raw}");
}
return $dt->startOfDay();
}
protected function peopleCountingSleepMs(): int
{
$n = (int) config('services.people_counting.sleep_ms', 200);
return max(0, min($n, 5000));
}
}