Passed
Push — master ( 5d0f2f...49b4e9 )
by Darko
10:54
created

RolePromotionObserver::saving()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 5
rs 10
cc 3
nc 2
nop 1
1
<?php
2
3
namespace App\Observers;
4
5
use App\Models\RolePromotion;
6
use Illuminate\Support\Carbon;
7
8
class RolePromotionObserver
9
{
10
    /**
11
     * Handle the RolePromotion "saving" event.
12
     * Automatically disable promotion if end date has passed
13
     */
14
    public function saving(RolePromotion $promotion): void
15
    {
16
        // If the promotion has an end date that has passed, automatically disable it
17
        if ($promotion->end_date && Carbon::now()->gt($promotion->end_date)) {
18
            $promotion->is_active = false;
19
        }
20
    }
21
22
    /**
23
     * Handle the RolePromotion "retrieved" event.
24
     * This helps ensure that when a promotion is loaded from the database,
25
     * we check if it should be disabled
26
     */
27
    public function retrieved(RolePromotion $promotion): void
28
    {
29
        // If the promotion has an end date that has passed but is still marked as active,
30
        // we update it (this will trigger saving event)
31
        if ($promotion->is_active && $promotion->end_date && Carbon::now()->gt($promotion->end_date)) {
32
            $promotion->is_active = false;
33
            $promotion->saveQuietly(); // Save without triggering events to avoid recursion
34
        }
35
    }
36
}
37
38