I am building a simple calendar with recurring events.
CalendarEvent.php
id
start_date
CalendarRecurringPattern.php
parent_id
pattern_type // daily, weekly, monthly, yearly ...
Using pattern_type
i build each following occurrence starting from start_date
, using a recursive function and Carbon::class
. What bugs me is the function getNextOccurrence()
, I'd like to refactor the if/else block because it's not very clean. Here it is:
use \Carbon\Carbon;
....
public function getNextOccurrence(Carbon $startDate) {
$pattern_type = $this->getPatternType() // daily, weekly...
if ($pattern_type == 'daily') {
$startDate->addDay();
} else if ($pattern_type == 'weekly') {
$startDate->addWeek();
} else if ($pattern_type == 'monthly') {
$startDate->addMonth();
} else if ($pattern_type == 'yearly') {
$startDate->addYear();
}
}
Thanks!
switch
, but honestly I don't see what's wrong with a lot of nested if statements. Once I was eager to refactor this kind of code, but now I learned to value its verbosity and clean meaning, so I wouldn't change it into something more "elegant" but less readable \$\endgroup\$