Просмотр файла app/Classes/Calendar.php

Размер файла: 2.04Kb
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. namespace App\Classes;
  6.  
  7. use App\Models\News;
  8.  
  9. class Calendar
  10. {
  11. /**
  12. * Возвращает календарь
  13. *
  14. * @param int $time
  15. *
  16. * @return string календарь
  17. */
  18. public function getCalendar(int $time = SITETIME): string
  19. {
  20. [$date['day'], $date['month'], $date['year']] = explode('.', dateFixed($time, 'j.n.Y', true));
  21. $date = array_map('intval', $date);
  22. $startMonth = mktime(0, 0, 0, $date['month'], 1, $date['year']);
  23. $endMonth = strtotime('+1 month', $startMonth);
  24.  
  25. $news = News::query()
  26. ->where('created_at', '>=', $startMonth)
  27. ->where('created_at', '<', $endMonth)
  28. ->get();
  29.  
  30. $newsIds = [];
  31. if ($news->isNotEmpty()) {
  32. foreach ($news as $data) {
  33. $curDay = dateFixed($data->created_at, 'j');
  34. $newsIds[$curDay] = $data->id;
  35. }
  36. }
  37.  
  38. $calendar = $this->makeCalendar($date['month'], $date['year']);
  39.  
  40. return view('app/_calendar', compact('calendar', 'date', 'time', 'newsIds'));
  41. }
  42.  
  43. /**
  44. * Формирует календарь
  45. *
  46. * @param int $month месяц
  47. * @param int $year год
  48. *
  49. * @return array сформированный массив
  50. */
  51. protected function makeCalendar(int $month, int $year): array
  52. {
  53. $date = date('w', mktime(0, 0, 0, $month, 1, $year));
  54.  
  55. if ($date === 0) {
  56. $date = 7;
  57. }
  58.  
  59. $n = - ($date-2);
  60. $cal = [];
  61. for ($y = 0; $y < 6; $y++) {
  62. $row = [];
  63. $notEmpty = false;
  64. for ($x = 0; $x < 7; $x++, $n++) {
  65. if (checkdate($month, $n, $year)) {
  66. $row[] = $n;
  67. $notEmpty = true;
  68. } else {
  69. $row[] = null;
  70. }
  71. }
  72.  
  73. if (! $notEmpty) {
  74. break;
  75. }
  76.  
  77. $cal[] = $row;
  78. }
  79. return $cal;
  80. }
  81. }