Completed
Push — master ( 896b70...2ed772 )
by Younes
07:16
created

RatingQueryBuilder   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 65
rs 10
c 0
b 0
f 0
wmc 8
lcom 1
cbo 2

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A from() 0 6 1
A to() 0 6 1
A user() 0 8 3
A rateable() 0 13 1
A getQuery() 0 4 1
1
<?php
2
3
namespace Yoeunes\Rateable\Builders;
4
5
use Yoeunes\Rateable\Traits\Rateable;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Database\Query\JoinClause;
8
use Yoeunes\Rateable\Exceptions\UserDoestNotHaveID;
9
use Illuminate\Database\Eloquent\Relations\MorphMany;
10
use Yoeunes\Rateable\Exceptions\ModelDoesNotUseRateableTrait;
11
12
class RatingQueryBuilder
13
{
14
    protected $query = null;
15
16
    public function __construct(MorphMany $query)
17
    {
18
        $this->query = $query;
19
    }
20
21
    public function from($date)
22
    {
23
        $this->query = $this->query->where('created_at', '>=', date_transformer($date));
24
25
        return $this;
26
    }
27
28
    public function to($date)
29
    {
30
        $this->query = $this->query->where('created_at', '<=', date_transformer($date));
31
32
        return $this;
33
    }
34
35
    /**
36
     * @param $user
37
     *
38
     * @return RatingQueryBuilder
39
     *
40
     * @throws \Throwable
41
     */
42
    public function user($user)
43
    {
44
        throw_if($user instanceof Model && empty($user->id), UserDoestNotHaveID::class, 'User object does not have ID');
45
46
        $this->query = $this->query->where('user_id', $user instanceof Model ? $user->id : $user);
47
48
        return $this;
49
    }
50
51
    /**
52
     * @param Model $rateable
53
     *
54
     * @return RatingQueryBuilder
55
     *
56
     * @throws \Throwable
57
     */
58
    public function rateable(Model $rateable)
59
    {
60
        throw_unless(in_array(Rateable::class, class_uses_recursive($rateable)), ModelDoesNotUseRateableTrait::class, get_class($rateable).' does not use the Rateable Trait');
61
62
        $this->query = $this->query
63
            ->leftJoin('ratings', function (JoinClause $join) use ($rateable) {
64
                $join
65
                    ->on('ratings.rateable_id', $rateable->getTable() . '.id')
66
                    ->where('ratings.rateable_type', morph_type($rateable));
67
            });
68
69
        return $this;
70
    }
71
72
    public function getQuery()
73
    {
74
        return $this->query;
75
    }
76
}
77