BackflowPeriod.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. <?php
  2. namespace App\Support;
  3. use Carbon\CarbonImmutable;
  4. use Illuminate\Support\Facades\DB;
  5. final class BackflowPeriod
  6. {
  7. public const TIMEZONE = 'Asia/Shanghai';
  8. public const DAILY_FROM_KEY = 'backflow_daily_from';
  9. public static function dailyFrom(): ?string
  10. {
  11. return DB::connection()->getSchemaBuilder()->hasTable('share_system_state')
  12. ? DB::table('share_system_state')->where('key', self::DAILY_FROM_KEY)->value('value') : null;
  13. }
  14. public static function forDate(string $date, ?string $dailyFrom): string
  15. {
  16. return $dailyFrom !== null && $date >= $dailyFrom ? $date : substr($date, 0, 7);
  17. }
  18. /** Inclusive start and exclusive end, both in Beijing. */
  19. public static function bounds(string $period, ?string $dailyFrom): array
  20. {
  21. if (strlen($period) === 10) {
  22. return [$period, CarbonImmutable::parse($period, self::TIMEZONE)->addDay()->toDateString()];
  23. }
  24. $start = $period . '-01';
  25. $end = CarbonImmutable::parse($start, self::TIMEZONE)->addMonth()->toDateString();
  26. return [$start, $dailyFrom === null ? $end : max($start, min($end, $dailyFrom))];
  27. }
  28. public static function waitsForSettlement(string $period, ?string $dailyFrom): bool
  29. {
  30. return strlen($period) === 10 || ($dailyFrom !== null && $period === substr($dailyFrom, 0, 7));
  31. }
  32. }