1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Xetaravel\Listeners\Subscribers; |
6
|
|
|
|
7
|
|
|
use Illuminate\Events\Dispatcher; |
8
|
|
|
use Xetaravel\Events\Discuss\PostWasSolvedEvent; |
9
|
|
|
use Xetaravel\Models\Ruby; |
10
|
|
|
|
11
|
|
|
class RubySubscriber |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* The rubies earned for the related event. |
15
|
|
|
* |
16
|
|
|
* @var array |
17
|
|
|
*/ |
18
|
|
|
protected array $rubies = [ |
19
|
|
|
PostWasSolvedEvent::class => 100 |
20
|
|
|
]; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* The events mapping to the listener function. |
24
|
|
|
* |
25
|
|
|
* @var array |
26
|
|
|
*/ |
27
|
|
|
protected array $events = [ |
28
|
|
|
PostWasSolvedEvent::class => 'handlePostWasSolved', |
29
|
|
|
]; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Create the ruby. |
33
|
|
|
* |
34
|
|
|
* @param array $data The data used to create the ruby. |
35
|
|
|
* |
36
|
|
|
* @return bool |
37
|
|
|
*/ |
38
|
|
|
protected function create(array $data): bool |
39
|
|
|
{ |
40
|
|
|
if (!isset($data['data'])) { |
41
|
|
|
$data['data'] = []; |
42
|
|
|
} |
43
|
|
|
$ruby = Ruby::create($data); |
44
|
|
|
|
45
|
|
|
switch ($ruby->event_type) { |
|
|
|
|
46
|
|
|
case PostWasSolvedEvent::class: |
47
|
|
|
$ruby->user->increment('rubies_total', $this->rubies[PostWasSolvedEvent::class]); |
|
|
|
|
48
|
|
|
break; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return !(is_null($ruby)); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Register the listeners for the subscriber. |
56
|
|
|
* |
57
|
|
|
* @param Dispatcher $events |
58
|
|
|
* |
59
|
|
|
* @return void |
60
|
|
|
*/ |
61
|
|
|
public function subscribe(Dispatcher $events): void |
62
|
|
|
{ |
63
|
|
|
foreach ($this->events as $event => $action) { |
64
|
|
|
$events->listen($event, self::class . '@' . $action); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* Handle a PostWasSolved event. |
70
|
|
|
* |
71
|
|
|
* @param PostWasSolvedEvent $event The event that was fired. |
72
|
|
|
* |
73
|
|
|
* @return bool |
74
|
|
|
*/ |
75
|
|
|
public function handlePostWasSolved(PostWasSolvedEvent $event): bool |
76
|
|
|
{ |
77
|
|
|
$data = [ |
78
|
|
|
'user_id' => $event->discussPost->user_id, |
79
|
|
|
'obtainable_id' => $event->discussPost->getKey(), |
80
|
|
|
'obtainable_type' => get_class($event->discussPost), |
81
|
|
|
'event_type' => PostWasSolvedEvent::class |
82
|
|
|
]; |
83
|
|
|
|
84
|
|
|
return $this->create($data); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|