44 lines
1.4 KiB
PHP
44 lines
1.4 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace DishPlanner\UserDish\Actions;
|
||
|
|
|
||
|
|
use App\Models\MinimumRecurrence;
|
||
|
|
use App\Models\UserDish;
|
||
|
|
use App\Models\UserDishRecurrence;
|
||
|
|
use App\Models\WeeklyRecurrence;
|
||
|
|
use DishPlanner\UserDish\Exceptions\InvalidRecurrenceTypeException;
|
||
|
|
use Illuminate\Support\Arr;
|
||
|
|
use Illuminate\Support\Collection;
|
||
|
|
|
||
|
|
class SyncRecurrencesForUserDishAction
|
||
|
|
{
|
||
|
|
/**
|
||
|
|
* @throws InvalidRecurrenceTypeException
|
||
|
|
*/
|
||
|
|
public function execute(UserDish $userDish, Collection $recurrences): UserDish
|
||
|
|
{
|
||
|
|
$userDish->recurrences()
|
||
|
|
->each(function (UserDishRecurrence $recurrence) {
|
||
|
|
$recurrence->recurrence->delete();
|
||
|
|
$recurrence->delete();
|
||
|
|
});
|
||
|
|
|
||
|
|
$recurrences->each(function (array $recurrence) use ($userDish) {
|
||
|
|
$recurrenceType = Arr::get($recurrence, 'type');
|
||
|
|
$recurrenceValue = Arr::get($recurrence, 'value');
|
||
|
|
|
||
|
|
if (! $recurrenceType || ! $recurrenceValue) {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
match ($recurrenceType) {
|
||
|
|
WeeklyRecurrence::class => (new CreateFixedRecurrenceAction())->execute($userDish, $recurrenceType, $recurrenceValue),
|
||
|
|
MinimumRecurrence::class => (new CreateMinimumRecurrenceAction())->execute($userDish, $recurrenceType, $recurrenceValue),
|
||
|
|
default => throw new InvalidRecurrenceTypeException(),
|
||
|
|
};
|
||
|
|
});
|
||
|
|
|
||
|
|
return $userDish->refresh();
|
||
|
|
}
|
||
|
|
}
|