Test Failed
Push — master ( ba1259...4303e9 )
by Younes
01:47
created

VoteBuilder::uniqueVoteForUsers()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
c 0
b 0
f 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
namespace Yoeunes\Rateable;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Database\Eloquent\Relations\Relation;
7
use Yoeunes\Voteable\Exceptions\EmptyUser;
8
use Yoeunes\Voteable\Exceptions\ModelDoesNotUseVoteableTrait;
9
use Yoeunes\Voteable\Exceptions\UserDoestNotHaveID;
10
use Yoeunes\Voteable\Exceptions\VoteableModelNotFound;
11
use Yoeunes\Voteable\Models\Vote;
12
use Yoeunes\Voteable\Traits\Voteable;
13
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)
30
    {
31
        throw_if($user instanceof Model && empty($user->id), UserDoestNotHaveID::class, 'User object does not have ID');
32
33
        $this->user = $user instanceof Model ? $user->id : $user;
34
35
        return $this;
36
    }
37
38
    /**
39
     * @param Model $voteable
40
     *
41
     * @return VoteBuilder
42
     *
43
     * @throws \Throwable
44
     */
45
    public function voteable(Model $voteable)
46
    {
47
        throw_unless(
48
            in_array(Voteable::class, class_uses_recursive($voteable)),
49
            ModelDoesNotUseVoteableTrait::class,
50
            get_class($voteable).' does not use the Voteable Trait'
51
        );
52
53
        $this->voteable = $voteable;
54
55
        return $this;
56
    }
57
58
    /**
59
     * @param bool $unique
60
     *
61
     * @return VoteBuilder
62
     */
63
    public function uniqueVoteForUsers(bool $unique)
64
    {
65
        $this->uniqueVoteForUsers = $unique;
66
67
        return $this;
68
    }
69
70
    /**
71
     * @param int $score
72
     *
73
     * @return Vote
74
     *
75
     * @throws \Throwable
76
     */
77
    public function score(int $score)
78
    {
79
        throw_if(empty($this->user), EmptyUser::class, 'Empty user');
80
81
        throw_if(empty($this->voteable->id), VoteableModelNotFound::class, 'Voteable model not found');
82
83
        $data = [
84
            'user_id'       => $this->user,
85
            'voteable_id'   => $this->voteable->id,
86
            'voteable_type' => Relation::getMorphedModel(get_class($this->voteable)) ?? get_class($this->voteable),
87
        ];
88
89
        $vote = $this->uniqueVoteForUsers ? Vote::firstOrNew($data) : (new Vote())->fill($data);
90
91
        $vote->score = $score;
92
93
        $vote->save();
94
95
        return $vote;
96
    }
97
}
98