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