Last active
January 6, 2025 12:14
-
-
Save vijinho/1a9cec54f3542ef2d48f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Validate and adjust year and month parameters, calculate date range for a complete whole month, | |
* and add MySQL date and Unix timestamp values to the params. | |
* | |
* Default to current year and month if there's a problem. | |
* | |
* @param array $params - requires 'year' and 'month' as int or will default to current values | |
* @return array | |
*/ | |
function parseTimeParams(array $params) | |
{ | |
// Set the timezone securely | |
date_default_timezone_set('Europe/London'); | |
// Get current year and month if not provided | |
$currentYear = date('Y'); | |
$currentMonth = (int) date('n'); | |
// Validate and set the year parameter | |
$year = array_key_exists('year', $params) ? (int) $params['year'] : null; | |
$year = validateYear($year, $currentYear); | |
// Validate and set the month parameter | |
$month = array_key_exists('month', $params) ? (int) $params['month'] : null; | |
$month = validateMonth($month, $currentMonth); | |
$params['year'] = $year; | |
$params['month'] = $month; | |
$params['monthName'] = date("F", mktime(0, 0, 0, $month)); | |
// Calculate first and last date/times of the month | |
$dateFrom = sprintf("%04d-%02d-01 00:00:00", $year, $month); | |
$dateTo = date('Y-m-t 23:59:59', strtotime($dateFrom)); | |
// Unix timestamp of first & last date/times of the month | |
$params['timeFrom'] = strtotime($dateFrom); | |
$params['timeTo'] = strtotime($dateTo); | |
return $params; | |
} | |
/** | |
* Validate and sanitize year input. | |
* | |
* @param int|null $year - The year to validate | |
* @param int $currentYear - Current year for default value | |
* @return int - Validated or sanitized year | |
*/ | |
function validateYear(?int $year, int $currentYear): int | |
{ | |
if (is_null($year) || empty($year)) { | |
return $currentYear; | |
} elseif ($year > $currentYear) { | |
return $currentYear; | |
} elseif ($year < 2010) { | |
return 2010; | |
} | |
return $year; | |
} | |
/** | |
* Validate and sanitize month input. | |
* | |
* @param int|null $month - The month to validate | |
* @param int $currentMonth - Current month for default value | |
* @return int - Validated or sanitized month | |
*/ | |
function validateMonth(?int $month, int $currentMonth): int | |
{ | |
if (is_null($month) || empty($month)) { | |
return $currentMonth; | |
} elseif ($month > 12 || $month < 1) { | |
return $currentMonth; | |
} | |
return $month; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment