Update pagex.class.php

Fix deprecated dynamic property creation and week calculation in relativeTime function

- Resolved deprecated warning by avoiding dynamic property creation on DateInterval object.
- Calculated weeks separately and included them correctly in the output string.
- Adjusted the logic to handle weeks within the string array without creating a dynamic property.
- Ensured compatibility with PHP 8.2 and higher, where dynamic properties are deprecated.

This fix prevents the "Deprecated: Creation of dynamic property DateInterval::$w is deprecated" warning and correctly formats the relative time string.
This commit is contained in:
basteyy 2024-07-06 23:05:51 +02:00 committed by Kazhnuz
parent 66dbfd185c
commit 6964cc2b6a

View file

@ -543,38 +543,45 @@ class Page
// $complete = false : short version // $complete = false : short version
// $complete = true : full version // $complete = true : full version
public function relativeTime($complete = false) public function relativeTime($complete = false)
{ {
$current = new DateTime; $current = new DateTime;
$past = new DateTime($this->getValue('dateRaw')); $past = new DateTime($this->getValue('dateRaw'));
$elapsed = $current->diff($past); $elapsed = $current->diff($past);
$elapsed->w = floor($elapsed->d / 7); // Calculate weeks separately
$elapsed->d -= $elapsed->w * 7; $weeks = floor($elapsed->d / 7);
$elapsed->d -= $weeks * 7;
$string = array( $string = array(
'y' => 'year', 'y' => 'year',
'm' => 'month', 'm' => 'month',
'w' => 'week', 'w' => $weeks,
'd' => 'day', 'd' => 'day',
'h' => 'hour', 'h' => 'hour',
'i' => 'minute', 'i' => 'minute',
's' => 'second', 's' => 'second',
); );
foreach ($string as $key => &$value) { foreach ($string as $key => &$value) {
if ($elapsed->$key) { if ($key == 'w') {
$value = $elapsed->$key . ' ' . $value . ($elapsed->$key > 1 ? 's' : ' '); if ($weeks > 0) {
} else { $value = $weeks . ' week' . ($weeks > 1 ? 's' : '');
unset($string[$key]); } else {
} unset($string[$key]);
} }
} elseif ($elapsed->$key) {
$value = $elapsed->$key . ' ' . $value . ($elapsed->$key > 1 ? 's' : '');
} else {
unset($string[$key]);
}
}
if (!$complete) { if (!$complete) {
$string = array_slice($string, 0, 1); $string = array_slice($string, 0, 1);
} }
return $string ? implode(', ', $string) . ' ago' : 'Just now'; return $string ? implode(', ', $string) . ' ago' : 'Just now';
} }
// Returns the value from the field, false if the fields doesn't exists // Returns the value from the field, false if the fields doesn't exists
// If you set the $option as TRUE, the function returns an array with all the values of the field // If you set the $option as TRUE, the function returns an array with all the values of the field