I'm trying to calculate a 'loyalty' score on Users. I have an Entries field history, with Entries like 2023, 2022, 2021 etc.
I want to calculate the number of consecutive years, going backward from the current year. So for example, a user with 2023, 2022, 2021 would have a loyalty score of 3. A user with 2022 and 2021 would have a loyalty score of 0 because they don't have a 2023 Membership. Should they buy one, they would immediately have 3 years of loyalty.
One additional problem is that these entries might not be in order in the field. They might be in order like 2019, 2022, 2020, 2023, 2021.
I previously had this working with tags, but with 4.4 and 5 coming soon I want to Entrify everything.
Here's my attempt based on that, but my loyalty value is only ever 0 or 1. I guess the previousYear part isn't working. Does anyone have ideas on fixing this or a better way to do it?
$currentYear = date('Y');
$previousYear = null;
$history = $user->history->all();
$loyalty = 0;
foreach ($history as $item) {
$year = $item->title;
if ($year === $currentYear) {
$loyalty++;
$previousYear = $year - 1;
} elseif ($previousYear !== null && $year === $previousYear) {
$loyalty++;
$previousYear = $year - 1;
}
}
$user->setFieldValue('loyalty', $loyalty);