CategoriesWidgetComposer::compose()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 15
ccs 0
cts 12
cp 0
rs 9.4285
cc 1
eloc 9
nc 1
nop 1
crap 2
1
<?php namespace Arcanesoft\Blog\ViewComposers\Front\Widgets;
2
3
use Arcanesoft\Blog\Entities\PostStatus;
4
use Arcanesoft\Blog\Models\Category;
5
use Arcanesoft\Blog\ViewComposers\AbstractComposer;
6
use Carbon\Carbon;
7
use Illuminate\Contracts\View\View;
8
use Illuminate\Database\Eloquent\Builder;
9
10
/**
11
 * Class     CategoriesWidgetComposer
12
 *
13
 * @package  Arcanesoft\Blog\ViewComposers\Front\Widgets
14
 * @author   ARCANEDEV <[email protected]>
15
 */
16
class CategoriesWidgetComposer extends AbstractComposer
17
{
18
    /* -----------------------------------------------------------------
19
     |  Constants
20
     | -----------------------------------------------------------------
21
     */
22
23
    const VIEW = 'blog::front._composers.widgets.categories-widget';
24
25
    /* -----------------------------------------------------------------
26
     |  Main Methods
27
     | -----------------------------------------------------------------
28
     */
29
30
    /**
31
     * Compose the view.
32
     *
33
     * @param  \Illuminate\Contracts\View\View  $view
34
     */
35
    public function compose(View $view)
36
    {
37
        $categories = Category::with('posts')
0 ignored issues
show
Bug introduced by
The method whereHas does only exist in Illuminate\Database\Eloquent\Builder, but not in Illuminate\Database\Eloquent\Model.

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...
38
            ->whereHas('posts', function (Builder $b) {
39
                // TODO: Try to export this code with model's scope ?
40
                $b->where('is_draft', false)
41
                  ->where('published_at', '<=', Carbon::now());
42
            })
43
            ->get()
44
            ->sortByDesc(function(Category $category) {
45
                return $category->posts->count();
46
            });
47
48
        $view->with('categoriesWidgetItems', $categories);
49
    }
50
}
51