Passed
Push — 5.0.0 ( f07a46...357374 )
by Fèvre
05:39
created

DiscussConversationObserver   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
dl 0
loc 56
rs 10
c 1
b 0
f 0
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A deleting() 0 33 5
A creating() 0 4 2
A updating() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Xetaravel\Observers;
6
7
use Illuminate\Support\Facades\Auth;
8
use Xetaravel\Models\DiscussConversation;
9
use Xetaravel\Models\Repositories\DiscussConversationRepository;
10
11
class DiscussConversationObserver
12
{
13
    /**
14
     * Handle the "creating" event.
15
     */
16
    public function creating(DiscussConversation $discussConversation): void
17
    {
18
        if (is_null($discussConversation->user_id)) {
0 ignored issues
show
introduced by
The condition is_null($discussConversation->user_id) is always false.
Loading history...
19
            $discussConversation->user_id = Auth::id();
20
        }
21
    }
22
23
    /**
24
     * Handle the "updating" event.
25
     */
26
    public function updating(DiscussConversation $discussConversation): void
27
    {
28
        $discussConversation->generateSlug();
29
    }
30
31
    /**
32
     * Handle the "deleting" event.
33
     */
34
    public function deleting(DiscussConversation $discussConversation): void
35
    {
36
        $category = $discussConversation->category;
37
38
        // If the conversation is the last_conversation of the category,
39
        // find the new last_conversation and update the category.
40
        if ($category->last_conversation_id == $discussConversation->getKey()) {
41
            $previousConversation = DiscussConversationRepository::findPreviousConversation($discussConversation);
42
43
            if (is_null($previousConversation)) {
44
                $category->last_conversation_id = null;
45
            } else {
46
                $category->last_conversation_id = $previousConversation->getKey();
47
            }
48
49
            $category->save();
50
        }
51
52
        // Set the foreign keys to null, else it won't delete since it delete
53
        // the posts before the conversation.
54
        $discussConversation->first_post_id = null;
55
        $discussConversation->last_post_id = null;
56
        $discussConversation->solved_post_id = null;
57
        $discussConversation->save();
58
59
        // We need to do this to refresh the countable cache `discuss_post_count` of the user.
60
        foreach ($discussConversation->posts as $post) {
61
            $post->delete();
62
        }
63
64
        // It don't delete the logs, so we need to do it manually.
65
        foreach ($discussConversation->discussLogs as $log) {
66
            $log->delete();
67
        }
68
    }
69
}
70