1
|
|
|
<?php |
2
|
|
|
namespace Xetaravel\Listeners\Subscribers; |
3
|
|
|
|
4
|
|
|
use Xetaravel\Events\Rubies\PostWasSolvedEvent; |
5
|
|
|
use Xetaravel\Models\Ruby; |
6
|
|
|
use Xetaravel\Models\User; |
7
|
|
|
|
8
|
|
|
class RubySubscriber |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* The rubies earned for the related event. |
12
|
|
|
* |
13
|
|
|
* @var array |
14
|
|
|
*/ |
15
|
|
|
protected $rubies = [ |
16
|
|
|
PostWasSolvedEvent::class => 100 |
17
|
|
|
]; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* The events mapping to the listener function. |
21
|
|
|
* |
22
|
|
|
* @var array |
23
|
|
|
*/ |
24
|
|
|
protected $events = [ |
25
|
|
|
PostWasSolvedEvent::class => 'postWasSolved', |
26
|
|
|
]; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Register the listeners for the subscriber. |
30
|
|
|
* |
31
|
|
|
* @param Illuminate\Events\Dispatcher $events |
32
|
|
|
* |
33
|
|
|
* @return void |
34
|
|
|
*/ |
35
|
|
|
public function subscribe($events) |
36
|
|
|
{ |
37
|
|
|
foreach ($this->events as $event => $action) { |
38
|
|
|
$events->listen($event, RubySubscriber::class . '@' . $action); |
39
|
|
|
} |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Handle a PostWasSolved event. |
44
|
|
|
* |
45
|
|
|
* @param \Xetaravel\Events\Rubies\PostWasSolvedEvent $event The event that was fired. |
46
|
|
|
* |
47
|
|
|
* @return bool |
48
|
|
|
*/ |
49
|
|
View Code Duplication |
public function postWasSolved(PostWasSolvedEvent $event) |
|
|
|
|
50
|
|
|
{ |
51
|
|
|
$data = [ |
52
|
|
|
'user_id' => $event->post->user_id, |
53
|
|
|
'obtainable_id' => $event->post->getKey(), |
54
|
|
|
'obtainable_type' => get_class($event->post), |
55
|
|
|
'event_type' => PostWasSolvedEvent::class |
56
|
|
|
]; |
57
|
|
|
|
58
|
|
|
return $this->create($data); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Create the ruby. |
63
|
|
|
* |
64
|
|
|
* @param array $data The data used to create the ruby. |
65
|
|
|
* |
66
|
|
|
* @return bool |
67
|
|
|
*/ |
68
|
|
|
protected function create(array $data) : bool |
69
|
|
|
{ |
70
|
|
|
if (!isset($data['data'])) { |
71
|
|
|
$data['data'] = []; |
72
|
|
|
} |
73
|
|
|
$ruby = Ruby::create($data); |
74
|
|
|
|
75
|
|
|
switch ($ruby->event_type) { |
76
|
|
|
case PostWasSolvedEvent::class: |
77
|
|
|
$ruby->user->increment('rubies_total', $this->rubies[PostWasSolvedEvent::class]); |
78
|
|
|
break; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
return !(is_null($ruby)); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.