SproutCMS

This is the code documentation for the SproutCMS project

source of /sprout/Helpers/Calendar.php

  1. <?php
  2. /*
  3.  * Copyright (C) 2017 Karmabunny Pty Ltd.
  4.  *
  5.  * This file is a part of SproutCMS.
  6.  *
  7.  * SproutCMS is free software: you can redistribute it and/or modify it under the terms
  8.  * of the GNU General Public License as published by the Free Software Foundation, either
  9.  * version 2 of the License, or (at your option) any later version.
  10.  *
  11.  * For more information, visit <http://getsproutcms.com>.
  12.  */
  13.  
  14. namespace Sprout\Helpers;
  15.  
  16. use DateTime;
  17. use Sprout\Helpers\View;
  18.  
  19. /**
  20.  * Renders a calendar
  21.  */
  22. class Calendar
  23. {
  24. /**
  25.   * Renders calendar HTML
  26.   *
  27.   * @param int $month 1 through to 12 (Jan - Dec)
  28.   * @param int $year
  29.   * @param callable $callback Render inner HTML for the cells
  30.   * @param array $options [week_begins,day_format,show_month,month_format]
  31.   * @return string HTML
  32.   */
  33. public static function render($month, $year, $callback, $options = null)
  34. {
  35. $month = (int) $month;
  36. $year = (int) $year;
  37. $day_names = [];
  38.  
  39. // Backwards compatibility
  40. if (is_int($options)) {
  41. $day = (int) $options;
  42. $options = [];
  43. $options['week_begins'] = $day;
  44. unset($day);
  45. }
  46.  
  47. if (!is_array($options)) $options = [];
  48.  
  49. if (empty($options['week_begins'])) $options['week_begins'] = 7;
  50. if (empty($options['day_format'])) $options['day_format'] = 'l';
  51. if (empty($options['show_month'])) $options['show_month'] = false;
  52. if (empty($options['month_format'])) $options['month_format'] = 'F Y';
  53.  
  54. $options['date_start'] = new DateTime('first day of ' . $year . '-' . $month);
  55. $options['date_end'] = new DateTime('last day of ' . $year . '-' . $month);
  56.  
  57. if ($options['week_begins'] == 1) {
  58. $options['week_ends'] = 7;
  59. } else {
  60. $options['week_ends'] = $options['week_begins'] - 1;
  61. }
  62.  
  63. while ($options['date_start']->format('N') != $options['week_begins']) {
  64. $options['date_start']->modify('-1 day');
  65. }
  66.  
  67. while ($options['date_end']->format('N') != $options['week_ends']) {
  68. $options['date_end']->modify('+1 day');
  69. }
  70.  
  71. while (count($day_names) < 7) {
  72. $day_names[] = date($options['day_format'], strtotime($options['week_begins'] + 4 . '-01-1970'));
  73.  
  74. if ($options['week_begins'] < 7) {
  75. $options['week_begins'] ++;
  76. } else {
  77. $options['week_begins'] = 1;
  78. }
  79. }
  80.  
  81. $view = new View('sprout/components/calendar');
  82. $view->year = $year;
  83. $view->month = $month;
  84. $view->day_names = $day_names;
  85. $view->callback = $callback;
  86. $view->options = $options;
  87.  
  88. return $view->render();
  89. }
  90. }
  91.