CommentQueryBuilder::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Yoeunes\Commentable;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Database\Query\JoinClause;
7
use Yoeunes\Commentable\Traits\Commentable;
8
use Illuminate\Database\Eloquent\Relations\Relation;
9
use Illuminate\Database\Eloquent\Relations\MorphMany;
10
use Yoeunes\Commentable\Exceptions\UserDoestNotHaveID;
11
use Yoeunes\Commentable\Exceptions\ModelDoesNotUseCommentableTrait;
12
13
class CommentQueryBuilder
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 CommentQueryBuilder
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 $commentable
54
     *
55
     * @return CommentQueryBuilder
56
     *
57
     * @throws \Throwable
58
     */
59
    public function voteable(Model $commentable)
60
    {
61
        throw_unless(in_array(Commentable::class, class_uses_recursive($commentable)), ModelDoesNotUseCommentableTrait::class, get_class($commentable).' does not use the Commentable Trait');
62
63
        $this->query = $this->query
64
            ->leftJoin('comments', function (JoinClause $join) use ($commentable) {
65
                $join
66
                    ->on('comments.commentable_id', $commentable->getTable() . '.id')
67
                    ->where('comments.commentable_type', in_array(get_class($commentable), Relation::morphMap()) ? array_search(get_class($commentable), Relation::morphMap()) : get_class($commentable));
68
            });
69
70
        return $this;
71
    }
72
73
    public function getQuery()
74
    {
75
        return $this->query;
76
    }
77
}
78