Files
lubo_comment_query/app/Util/VideoCalendarUtil.php
2026-07-29 09:10:18 +08:00

49 lines
1.5 KiB
PHP

<?php
namespace App\Util;
use Carbon\Carbon;
class VideoCalendarUtil
{
const TITLE_DATE_PATTERN = "/直播于\s*(?:(\d{4})_(\d{1,2})_(\d{1,2})|(\d{4})(\d{2})(\d{2}))/";
/**
* 从稿件标题解析直播日期,支持「直播于 20260111」与「直播于 2019_01_25」两种格式。
* 无法解析或日期非法时返回 null。
*/
public static function parse_live_date(?string $title): ?Carbon
{
if (!$title || !preg_match(static::TITLE_DATE_PATTERN, $title, $matches)) {
return null;
}
if ($matches[1] !== "") {
[$year, $month, $day] = [(int)$matches[1], (int)$matches[2], (int)$matches[3]];
} else {
[$year, $month, $day] = [(int)$matches[4], (int)$matches[5], (int)$matches[6]];
}
if (!checkdate($month, $day, $year)) {
return null;
}
return Carbon::createFromDate($year, $month, $day)->startOfDay();
}
/**
* 按直播日期分组稿件,返回 ['Y-m-d' => [video, ...]],按日期升序。
* 标题无法解析的稿件不会进入结果。
*/
public static function group_by_live_date(iterable $videos): array
{
$grouped = [];
foreach ($videos as $video) {
$date = static::parse_live_date($video->title ?? null);
if ($date === null) {
continue;
}
$grouped[$date->format("Y-m-d")][] = $video;
}
ksort($grouped);
return $grouped;
}
}