| 12345678910111213141516171819202122232425262728293031323334353637383940 |
- <?php
- namespace App\Support;
- use Illuminate\Support\Facades\Validator;
- final class ActivityPeriod
- {
- public static function forSave(array $input, bool $editing, bool $strictEnd = false): array
- {
- if ($editing && !array_key_exists('start_time', $input) && !array_key_exists('end_time', $input)) return [];
- $dates = [];
- foreach (['start_time', 'end_time'] as $key) {
- $value = $input[$key] ?? null;
- $dates[$key] = is_string($value) && trim($value) === '' ? null : $value;
- }
- Validator::make($dates, [
- 'start_time' => ['nullable', 'required_with:end_time', 'date'],
- 'end_time' => ['nullable', 'required_with:start_time', 'date', ($strictEnd ? 'after:' : 'after_or_equal:') . 'start_time'],
- ], [
- 'start_time.required_with' => '活动开始和结束时间必须同时填写或同时留空',
- 'end_time.required_with' => '活动开始和结束时间必须同时填写或同时留空',
- ])->validate();
- return array_map(static fn ($value) => $value === null ? null : strtotime($value), $dates);
- }
- public static function contains($start, $end, int $time): bool
- {
- return ($start === null && $end === null)
- || ($start !== null && $end !== null && (int)$start <= $time && (int)$end >= $time);
- }
- public static function active($query, int $time)
- {
- return $query->where(function ($q) use ($time) {
- $q->where(fn ($q) => $q->whereNull('start_time')->whereNull('end_time'))
- ->orWhere(fn ($q) => $q->where('start_time', '<=', $time)->where('end_time', '>=', $time));
- });
- }
- }
|