ActivityPeriod.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. <?php
  2. namespace App\Support;
  3. use Illuminate\Support\Facades\Validator;
  4. final class ActivityPeriod
  5. {
  6. public static function forSave(array $input, bool $editing, bool $strictEnd = false): array
  7. {
  8. if ($editing && !array_key_exists('start_time', $input) && !array_key_exists('end_time', $input)) return [];
  9. $dates = [];
  10. foreach (['start_time', 'end_time'] as $key) {
  11. $value = $input[$key] ?? null;
  12. $dates[$key] = is_string($value) && trim($value) === '' ? null : $value;
  13. }
  14. Validator::make($dates, [
  15. 'start_time' => ['nullable', 'required_with:end_time', 'date'],
  16. 'end_time' => ['nullable', 'required_with:start_time', 'date', ($strictEnd ? 'after:' : 'after_or_equal:') . 'start_time'],
  17. ], [
  18. 'start_time.required_with' => '活动开始和结束时间必须同时填写或同时留空',
  19. 'end_time.required_with' => '活动开始和结束时间必须同时填写或同时留空',
  20. ])->validate();
  21. return array_map(static fn ($value) => $value === null ? null : strtotime($value), $dates);
  22. }
  23. public static function contains($start, $end, int $time): bool
  24. {
  25. return ($start === null && $end === null)
  26. || ($start !== null && $end !== null && (int)$start <= $time && (int)$end >= $time);
  27. }
  28. public static function active($query, int $time)
  29. {
  30. return $query->where(function ($q) use ($time) {
  31. $q->where(fn ($q) => $q->whereNull('start_time')->whereNull('end_time'))
  32. ->orWhere(fn ($q) => $q->where('start_time', '<=', $time)->where('end_time', '>=', $time));
  33. });
  34. }
  35. }