1 | <?php |
||
14 | class VoteBuilder |
||
15 | { |
||
16 | protected $user; |
||
17 | |||
18 | protected $voteable; |
||
19 | |||
20 | protected $uniqueVoteForUsers = true; |
||
21 | |||
22 | /** |
||
23 | * @param Model|int $user |
||
24 | * |
||
25 | * @return VoteBuilder |
||
26 | * |
||
27 | * @throws \Throwable |
||
28 | */ |
||
29 | public function user($user) |
||
37 | |||
38 | /** |
||
39 | * @param Model $voteable |
||
40 | * |
||
41 | * @return VoteBuilder |
||
42 | * |
||
43 | * @throws \Throwable |
||
44 | */ |
||
45 | public function voteable(Model $voteable) |
||
53 | |||
54 | /** |
||
55 | * @param bool $unique |
||
56 | * |
||
57 | * @return VoteBuilder |
||
58 | */ |
||
59 | public function uniqueVoteForUsers(bool $unique) |
||
65 | |||
66 | /** |
||
67 | * @param int $amount |
||
68 | * |
||
69 | * @return Vote |
||
70 | * |
||
71 | * @throws \Throwable |
||
72 | */ |
||
73 | public function amount(int $amount) |
||
74 | { |
||
75 | throw_if(empty($this->user), EmptyUser::class, 'Empty user'); |
||
76 | |||
77 | throw_if(empty($this->voteable->id), VoteableModelNotFound::class, 'Voteable model not found'); |
||
78 | |||
79 | $data = [ |
||
80 | 'user_id' => $this->user, |
||
81 | 'voteable_id' => $this->voteable->id, |
||
82 | 'voteable_type' => Relation::getMorphedModel(get_class($this->voteable)) ?? get_class($this->voteable), |
||
83 | ]; |
||
84 | |||
85 | $vote = $this->uniqueVoteForUsers ? Vote::firstOrNew($data) : (new Vote())->fill($data); |
||
86 | |||
87 | $vote->amount = $amount; |
||
88 | |||
89 | $vote->save(); |
||
90 | |||
91 | return $vote; |
||
92 | } |
||
93 | |||
94 | /** |
||
95 | * @return Vote |
||
96 | * |
||
97 | * @throws \Throwable |
||
98 | */ |
||
99 | public function voteUp() |
||
103 | |||
104 | /** |
||
105 | * @return Vote |
||
106 | * |
||
107 | * @throws \Throwable |
||
108 | */ |
||
109 | public function voteDown() |
||
113 | } |
||
114 |