Completed
Push — master ( 338941...b877df )
by Christopher
01:12
created

PostBuilder::publishedLastWeek()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Chriscreates\Blog\Builders;
4
5
use Carbon\Carbon;
6
use Chriscreates\Blog\Category;
7
use Chriscreates\Blog\Post;
8
use Illuminate\Support\Collection;
9
10
class PostBuilder extends Builder
11
{
12
    /**
13
     * Return results where Posts are related for the current logged in user.
14
     *
15
     * @return \Chriscreates\Blog\Builders\PostBuilder
16
     */
17
    public function forCurrentUser() : PostBuilder
18
    {
19
        return $this->where('user_id', request()->user()->id ?? null);
20
    }
21
22
    /**
23
     * Return results where Posts have status.
24
     *
25
     * @param string $status
26
     * @return \Chriscreates\Blog\Builders\PostBuilder
27
     */
28
    public function status(string $status) : PostBuilder
29
    {
30
        return $this->where('status', $status);
31
    }
32
33
    /**
34
     * Return results where Posts have been published.
35
     *
36
     * @return \Chriscreates\Blog\Builders\PostBuilder
37
     */
38
    public function published() : PostBuilder
39
    {
40
        return $this->whereIn('status', [Post::PUBLISHED, Post::SCHEDULED])
0 ignored issues
show
Documentation Bug introduced by
The method whereIn does not exist on object<Chriscreates\Blog\Builders\PostBuilder>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
41
        ->where('published_at', '<=', Carbon::now());
42
    }
43
44
    /**
45
     * Return results where Posts have been scheduled to be published.
46
     *
47
     * @return \Chriscreates\Blog\Builders\PostBuilder
48
     */
49
    public function scheduled() : PostBuilder
50
    {
51
        return $this->where(function ($query) {
52
            return $query->where('status', Post::SCHEDULED)
53
          ->where('published_at', '>', Carbon::now());
54
        });
55
    }
56
57
    /**
58
     * Return results where Posts are drafted.
59
     *
60
     * @return \Chriscreates\Blog\Builders\PostBuilder
61
     */
62
    public function draft() : PostBuilder
63
    {
64
        return $this->where(function ($query) {
65
            return $query->where('status', Post::DRAFT)
66
          ->whereNull('published_at');
67
        });
68
    }
69
70
    /**
71
     * Return results where Posts are not yet published.
72
     *
73
     * @return \Chriscreates\Blog\Builders\PostBuilder
74
     */
75
    public function notPublished() : PostBuilder
76
    {
77
        return $this->where(function ($query) {
78
            return $query->draft();
79
        })->orWhere(function ($query) {
80
            return $query->scheduled();
81
        });
82
    }
83
84
    /**
85
     * Order Post results by latest published.
86
     *
87
     * @return \Chriscreates\Blog\Builders\PostBuilder
88
     */
89
    public function orderByLatest() : PostBuilder
90
    {
91
        return $this->orderBy('published_at', 'DESC');
0 ignored issues
show
Bug introduced by
The method orderBy() does not exist on Chriscreates\Blog\Builders\PostBuilder. Did you maybe mean orderByLatest()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
92
    }
93
94
    /**
95
     * Return results where Posts have been published last month.
96
     *
97
     * @return \Chriscreates\Blog\Builders\PostBuilder
98
     */
99
    public function publishedLastMonth() : PostBuilder
100
    {
101
        return $this->whereBetween('published_at', [
0 ignored issues
show
Documentation Bug introduced by
The method whereBetween does not exist on object<Chriscreates\Blog\Builders\PostBuilder>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
102
            Carbon::now()->subMonth(), Carbon::now(),
103
        ])->orderByLatest()->limit($limit);
0 ignored issues
show
Bug introduced by
The variable $limit does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
104
    }
105
106
    /**
107
     * Return results where Posts have been published last week.
108
     *
109
     * @return \Chriscreates\Blog\Builders\PostBuilder
110
     */
111
    public function publishedLastWeek() : PostBuilder
112
    {
113
        return $this->whereBetween('published_at', [
0 ignored issues
show
Documentation Bug introduced by
The method whereBetween does not exist on object<Chriscreates\Blog\Builders\PostBuilder>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
114
            Carbon::now()->subWeek(), Carbon::now(),
115
        ])->orderByLatest();
116
    }
117
118
    /**
119
     * Return results where Posts are related by the passed in Post Tags.
120
     *
121
     * @param \Chriscreates\Blog\Post $post
122
     * @return \Chriscreates\Blog\Builders\PostBuilder
123
     */
124
    public function relatedByPostTags(Post $post) : PostBuilder
125
    {
126
        return $this->whereHas('tags', function ($query) use ($post) {
0 ignored issues
show
Bug introduced by
The method where does only exist in Illuminate\Database\Eloquent\Builder, but not in Illuminate\Database\Eloq...ns\QueriesRelationships.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
127
            return $query->whereIn('name', $post->tags->pluck('name'));
128
        })->where('id', '!=', $post->id);
129
    }
130
131
    /**
132
     * Return results where Posts are related by the passed in Post Category.
133
     *
134
     * @param \Chriscreates\Blog\Post $post
135
     * @return \Chriscreates\Blog\Builders\PostBuilder
136
     */
137
    public function relatedByPostCategory(Post $post) : PostBuilder
138
    {
139
        return $this->whereHas('category', function ($query) use ($post) {
0 ignored issues
show
Bug introduced by
The method where does only exist in Illuminate\Database\Eloquent\Builder, but not in Illuminate\Database\Eloq...ns\QueriesRelationships.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
140
            return $query->where('id', $post->category->id);
141
        })->where('id', '!=', $post->id);
142
    }
143
144
    /**
145
     * Return results where Posts contain the Category(s) passed.
146
     *
147
     * @param $categories
148
     * @return \Chriscreates\Blog\Builders\PostBuilder
149
     */
150
    public function whereCategories($categories = null) : PostBuilder
151
    {
152
        // search by category name
153
        if (is_string($categories)) {
154
            return $this->whereCategory('name', $categories);
155
        }
156
157
        // search by category id
158
        if (is_int($categories)) {
159
            return $this->whereCategory('id', $categories);
160
        }
161
162
        // search by multiple categories
163
        if (is_array($categories)) {
164
            if (is_int($categories[0])) {
165
                $field = 'id';
166
            } else {
167
                $field = 'name';
168
            }
169
170
            return $this->whereCategory($field, $categories);
171
        }
172
173
        // search by category model
174
        if ($categories instanceof Category) {
175
            return $this->whereCategory('id', $categories->id);
176
        }
177
178
        // search by categories collection
179
        if ($categories instanceof Collection) {
180
            return $this->whereCategory('id', $categories->pluck('id')->toArray());
181
        }
182
183
        return $this;
184
    }
185
186
    /**
187
     * Return results where Posts contain the Category(s) passed.
188
     *
189
     * @param array $options
190
     * @return \Chriscreates\Blog\Builders\PostBuilder
191
     */
192
    public function whereCategory(...$options) : PostBuilder
193
    {
194
        $collection = collect([
195
            'field' => 'id',
196
            'operator' => '=',
197
            'value' => null,
198
        ]);
199
200
        // Search by field and value
201 View Code Duplication
        if (count($options) == 2) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
202
            $collection = $collection->replace(['field' => $options[0]])
203
            ->replace(['value' => $options[1]]);
204
        }
205
206
        // Search by field, operator and value
207 View Code Duplication
        if (count($options) == 3) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
208
            $collection = $collection->replace(['field' => $options[0]])
209
            ->replace(['operator' => $options[1]])
210
            ->replace(['value' => $options[2]]);
211
        }
212
213
        // $this->with('category');
214
215
        if (is_array($collection['value'])) {
216
            return $this->whereHas(
217
                'category',
218
                function ($query) use ($collection) {
219
                    return $query->whereIn(
220
                        $collection['field'],
221
                        $collection['value']
222
                    );
223
                }
224
            );
225
        }
226
227
        return $this->whereHas(
228
            'category',
229
            function ($query) use ($collection) {
230
                return $query->where(
231
                    $collection['field'],
232
                    $collection['operator'],
233
                    $collection['value']
234
                );
235
            }
236
        );
237
    }
238
}
239