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)) { |
|
|
|
|
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
|
|
|
|