UserDeletedObserver   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 31
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A cleanRelatedTopic() 0 11 3
A handle() 0 3 1
1
<?php
2
3
namespace App\Listeners;
4
5
use App\Entities\Topic;
6
use App\Entities\User;
7
use App\Repositories\TopicRepository;
8
9
class UserDeletedObserver
10
{
11
    /**
12
     * @var TopicRepository
13
     */
14
    private $topicRepository;
15
16
    public function __construct()
17
    {
18
        $this->topicRepository = app(TopicRepository::class);
19
    }
20
21
    public function handle(User $user)
22
    {
23
        $this->cleanRelatedTopic($user);
24
    }
25
26
    /**
27
     * @param User $user
28
     */
29
    public function cleanRelatedTopic(User $user): void
30
    {
31
        /** @var Topic[] $topics */
32
        app('log')->info("user {$user->id} deleted, remove related topics");
33
        $topics = $this->topicRepository->findAllBy('user_id', $user->id);
34
        foreach ($topics as $topic) {
35
            try {
36
                $topic->replies()->delete();
37
                $topic->delete();
38
            } catch (\Exception $e) {
39
                app('log')->error("remove topic failed! {$e->getMessage()}");
40
            }
41
        }
42
    }
43
}
44