Completed
Push — master ( fbfcb9...4fd533 )
by Song
02:36
created

LogController::index()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Encore\Admin\Controllers;
4
5
use Encore\Admin\Auth\Database\OperationLog;
6
use Encore\Admin\Grid;
7
use Illuminate\Support\Arr;
8
9
class LogController extends AdminController
10
{
11
    /**
12
     * {@inheritdoc}
13
     */
14
    protected function title()
15
    {
16
        return trans('admin.operation_log');
0 ignored issues
show
Bug Best Practice introduced by
The return type of return trans('admin.operation_log'); (Illuminate\Contracts\Tra...lator|string|array|null) is incompatible with the return type of the parent method Encore\Admin\Controllers\AdminController::title of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
17
    }
18
19
    /**
20
     * @return Grid
21
     */
22
    protected function grid()
23
    {
24
        $grid = new Grid(new OperationLog());
25
26
        $grid->model()->orderBy('id', 'DESC');
0 ignored issues
show
Bug introduced by
The method orderBy() does not exist on Encore\Admin\Grid\Model. Did you maybe mean resetOrderBy()?

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...
27
28
        $grid->column('id', 'ID')->sortable();
29
        $grid->column('user.name', 'User');
30
        $grid->column('method')->display(function ($method) {
31
            $color = Arr::get(OperationLog::$methodColors, $method, 'grey');
32
33
            return "<span class=\"badge bg-$color\">$method</span>";
34
        });
35
        $grid->column('path')->label('info');
0 ignored issues
show
Documentation Bug introduced by
The method label does not exist on object<Encore\Admin\Grid\Column>? 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...
36
        $grid->column('ip')->label('primary');
0 ignored issues
show
Documentation Bug introduced by
The method label does not exist on object<Encore\Admin\Grid\Column>? 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...
37
        $grid->column('input')->display(function ($input) {
38
            $input = json_decode($input, true);
39
            $input = Arr::except($input, ['_pjax', '_token', '_method', '_previous_']);
40
            if (empty($input)) {
41
                return '<code>{}</code>';
42
            }
43
44
            return '<pre>'.json_encode($input, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE).'</pre>';
45
        });
46
47
        $grid->column('created_at', trans('admin.created_at'));
48
49
        $grid->actions(function (Grid\Displayers\Actions $actions) {
50
            $actions->disableEdit();
51
            $actions->disableView();
52
        });
53
54
        $grid->disableCreateButton();
55
56
        $grid->filter(function (Grid\Filter $filter) {
57
            $userModel = config('admin.database.users_model');
58
59
            $filter->equal('user_id', 'User')->select($userModel::all()->pluck('name', 'id'));
60
            $filter->equal('method')->select(array_combine(OperationLog::$methods, OperationLog::$methods));
61
            $filter->like('path');
62
            $filter->equal('ip');
63
        });
64
65
        return $grid;
66
    }
67
68
    /**
69
     * @param mixed $id
70
     *
71
     * @return \Illuminate\Http\JsonResponse
72
     */
73
    public function destroy($id)
74
    {
75
        $ids = explode(',', $id);
76
77
        if (OperationLog::destroy(array_filter($ids))) {
78
            $data = [
79
                'status'  => true,
80
                'message' => trans('admin.delete_succeeded'),
81
            ];
82
        } else {
83
            $data = [
84
                'status'  => false,
85
                'message' => trans('admin.delete_failed'),
86
            ];
87
        }
88
89
        return response()->json($data);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

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...
90
    }
91
}
92