Completed
Push — datatables-fix ( e9c4b2...619c08 )
by Tony
02:59
created

SearchDataTable   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 203
Duplicated Lines 8.87 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 5
Bugs 1 Features 1
Metric Value
wmc 26
c 5
b 1
f 1
lcom 1
cbo 4
dl 18
loc 203
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
C ajax() 8 43 11
B query() 10 25 5
A html() 0 6 1
B getColumns() 0 61 6
A filename() 0 4 1
A getBuilderParameters() 0 12 1
A forType() 0 5 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * app/DataTables/General/SearchDataTable.php
4
 *
5
 * Datatable for search
6
 *
7
 * This program is free software: you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation, either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
 *
20
 * @package    LibreNMS
21
 * @link       http://librenms.org
22
 * @copyright  2016 Neil Lathwood
23
 * @author     Neil Lathwood <[email protected]>
24
 */
25
26
namespace App\DataTables\General;
27
28
use App\Models\General\IPv4;
29
use App\Models\General\IPv4Mac;
30
use App\Models\General\IPv6;
31
use App\Models\Port;
32
use Yajra\Datatables\Services\DataTable;
33
34
class SearchDataTable extends DataTable
35
{
36
37
    protected $type;
38
39
    /**
40
     * Display ajax response.
41
     *
42
     * @return \Illuminate\Http\JsonResponse
43
     */
44
    public function ajax()
45
    {
46
        if ($this->type !== "arp")
47
        {
48
            return $this->datatables
49
                ->eloquent($this->query())
50
                ->editColumn('hostname', function($data) {
0 ignored issues
show
Documentation introduced by
function ($data) { $.... $hostname . '</a>'; } is of type object<Closure>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
51
                    $hostname = is_null($data->device) ? trans('devices.text.deleted') : $data->device->hostname;
52
                    return '<a href="'.url("devices/".$data->device_id).'">'.$hostname.'</a>';
53
                })
54 View Code Duplication
                ->editColumn('ifName', function($data) {
0 ignored issues
show
Documentation introduced by
function ($data) { $...' . $ifName . '</a>'; } is of type object<Closure>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
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...
55
                    $ifName = is_null($data->ifName) ? trans('devices.text.deleted') : $data->ifName;
56
                    return '<a href="'.url("devices/".$data->device_id."/ports/".$data->port_id).'">'.$ifName.'</a>';
57
                })
58
                ->make(true);
59
        }
60
        else {
61
            return $this->datatables
62
                ->eloquent($this->query())
63
                ->editColumn('hostname', function($data) {
0 ignored issues
show
Documentation introduced by
function ($data) { $.... $hostname . '</a>'; } is of type object<Closure>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
64
                    $hostname = is_null($data->device) ? trans('devices.text.deleted') : $data->device->hostname;
65
                    return '<a href="'.url("devices/".$data->device_id).'">'.$hostname.'</a>';
66
                })
67 View Code Duplication
                ->editColumn('ifName', function($data) {
0 ignored issues
show
Documentation introduced by
function ($data) { $...' . $ifName . '</a>'; } is of type object<Closure>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
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...
68
                    $ifName = is_null($data->ifName) ? trans('devices.text.deleted') : $data->ifName;
69
                    return '<a href="'.url("devices/".$data->device_id."/ports/".$data->port_id).'">'.$ifName.'</a>';
70
                })
71
                ->addColumn('remote_device', function($data) {
0 ignored issues
show
Documentation introduced by
function ($data) { $...te_hostname . '</a>'; } is of type object<Closure>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
72
                    $remote_device = IPv4::where('ipv4_addresses.ipv4_address', $data->ipv4_address)->with('port.device')->first();
73
                    $remote_id = empty($remote_device->port->device->device_id) ? '' : $remote_device->port->device->device_id;
74
                    $remote_hostname = empty($remote_device->port->device->hostname) ? trans('devices.text.deleted') : $remote_device->port->device->hostname;
75
                    return '<a href="'.url("devices/".$remote_id).'">'.$remote_hostname.'</a>';
76
                })
77
                ->addColumn('remote_interface', function($data) {
0 ignored issues
show
Documentation introduced by
function ($data) { $...remote_port . '</a>'; } is of type object<Closure>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
78
                    $remote_device = IPv4::where('ipv4_addresses.ipv4_address', $data->ipv4_address)->with('port.device')->first();
79
                    $remote_id = empty($remote_device->port->device->device_id) ? '' : $remote_device->port->device->device_id;
80
                    $remote_port_id = empty($remote_device->port->port_id) ? '' : $remote_device->port->port_id;
81
                    $remote_port = empty($remote_device->port->ifName) ? trans('devices.text.deleted') : $remote_device->port->ifName;
82
                    return '<a href="'.url("devices/".$remote_id."/ports/".$remote_port_id).'">'.$remote_port.'</a>';
83
                })
84
                ->make(true);
85
        }
86
    }
87
88
    /**
89
     * Get the query object to be processed by datatables.
90
     *
91
     * @return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder
92
     */
93
    public function query()
94
    {
95
        if ($this->type === "ipv4")
96
        {
97
            $data = IPv4::join('ports', 'ports.port_id', '=', 'ipv4_addresses.port_id')->join('devices', 'devices.device_id', '=', 'ports.device_id')->select('ipv4_addresses.*', 'ports.*', 'devices.*');
98
            //FIXME We should use this once laravel-datatables supports it upstream $data = IPv4::with('port.device')->select('ipv4_addresses.*');
99
        }
100 View Code Duplication
        elseif ($this->type === "ipv6")
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...
101
        {
102
            $data = IPv6::join('ports', 'ports.port_id', '=', 'ipv6_addresses.port_id')->join('devices', 'devices.device_id', '=', 'ports.device_id')->select('ipv6_addresses.*', 'ports.*', 'devices.*');
103
            //FIXME We should use this once laravel-datatables supports it upstream $data = IPv6::with('port.device')->select('ipv6_addresses.*');
104
        }
105
        elseif ($this->type === "mac")
106
        {
107
            $data = Port::join('devices', 'devices.device_id', '=', 'ports.device_id')->select('ports.*', 'devices.*');
108
            //FIXME This is valid but stops us generalising this file so until the nested queries above are fixed then we default to joins
109
            //$data = Port::with('device')->select('ports.*');
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
110
        }
111 View Code Duplication
        elseif ($this->type === "arp")
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...
112
        {
113
            $data = IPv4Mac::join('ports', 'ports.port_id', '=', 'ipv4_mac.port_id')->join('devices', 'devices.device_id', '=', 'ports.device_id')->select('ipv4_mac.*', 'ports.*', 'devices.*');
114
            //FIXME We should use this once laravel-datatables supports it upstream $data = IPv4Mac::with('port.device')->select('ipv4_mac.*');
115
        }
116
        return $this->applyScopes($data);
0 ignored issues
show
Bug introduced by
The variable $data does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug Compatibility introduced by
The expression $this->applyScopes($data); of type Illuminate\Database\Quer...tabase\Eloquent\Builder adds the type Illuminate\Database\Query\Builder to the return on line 116 which is incompatible with the return type declared by the interface Yajra\Datatables\Contrac...ataTableContract::query of type Illuminate\Database\Eloquent\Builder.
Loading history...
117
    }
118
119
    /**
120
     * Optional method if you want to use html builder.
121
     *
122
     * @return \Yajra\Datatables\Html\Builder
123
     */
124
    public function html()
125
    {
126
        return $this->builder()
127
                    ->columns($this->getColumns())
128
                    ->parameters($this->getBuilderParameters());
129
    }
130
131
    /**
132
     * Get columns.
133
     *
134
     * @return array
135
     */
136
    private function getColumns()
137
    {
138
        $cols = [
139
            'hostname'  => [
140
                'title' => trans('devices.label.hostname'),
141
            ],
142
            'ifName'    => [
143
                'title' => trans('general.text.interface'),
144
            ],
145
        ];
146
        if ($this->type === "ipv4")
147
        {
148
            $cols = array_merge($cols, [
149
                'ipv4_address' => [
150
                    'title'    => trans('general.text.address'),
151
                ],
152
            ]);
153
        }
154
        if ($this->type === "ipv6")
155
        {
156
            $cols = array_merge($cols, [
157
                'ipv6_address' => [
158
                    'title'    => trans('general.text.address'),
159
                ],
160
            ]);
161
        }
162
        if ($this->type === "mac")
163
        {
164
            $cols = array_merge($cols, [
165
                'ifPhysAddress' => [
166
                    'title'    => trans('general.text.mac_address'),
167
                ],
168
            ]);
169
        }
170
        if ($this->type === "arp")
171
        {
172
            $cols = array_merge($cols, [
173
                'mac_address' => [
174
                    'title'   => trans('general.text.mac_address'),
175
                ],
176
                'ipv4_address' => [
177
                    'title'    => trans('general.text.address'),
178
                ],
179
                'remote_device'  => [
180
                    'searchable' => false,
181
                ],
182
                'remote_interface' => [
183
                    'searchable'   => false,
184
                ]
185
            ]);
186
        }
187
        if ($this->type !== "arp")
188
        {
189
            $cols = array_merge($cols, [
190
                'ifDescr'   => [
191
                    'title' => trans('general.text.port_descr'),
192
                ],
193
            ]);
194
        }
195
        return $cols;
196
    }
197
198
    /**
199
     * Get filename for export.
200
     *
201
     * @return string
202
     */
203
    protected function filename()
204
    {
205
        return 'search';
206
    }
207
208
    /**
209
     * Get Builder Params
210
     *
211
     * @return array
212
     */
213
    protected function getBuilderParameters()
214
    {
215
        return [
0 ignored issues
show
Best Practice introduced by
The expression return array('dom' => '<...', 'reset', 'reload')); seems to be an array, but some of its elements' types (string) are incompatible with the return type of the parent method Yajra\Datatables\Service...e::getBuilderParameters of type array<string,array>.

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 new Author('Johannes');
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return '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...
216
            'dom' => "<'row'<'col-sm-3'l><'col-sm-6 text-center'B><'col-sm-3'f>>".
217
                "<'row'<'col-sm-12'tr>>".
218
                "<'row'<'col-sm-5'i><'col-sm-7'p>>",
219
            'lengthMenu' => [[25, 50, 100, -1], [25, 50, 100, "All"]],
220
            'buttons' => [
221
                'csv', 'excel', 'pdf', 'print', 'reset', 'reload',
222
            ],
223
        ];
224
    }
225
226
227
    /**
228
     * @param string $type
229
     */
230
    public function forType($type)
231
    {
232
        $this->type = $type;
233
        return $this;
234
    }
235
236
}
237