BelongsTo   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Importance

Changes 0
Metric Value
wmc 3
lcom 0
cbo 4
dl 0
loc 48
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A model() 0 14 2
A placeholder() 0 13 1
1
<?php
2
3
namespace Yajra\DataTables\Html\Editor\Fields;
4
5
use Illuminate\Support\Str;
6
use Illuminate\Database\Eloquent\Builder;
7
8
class BelongsTo extends Select
9
{
10
    /**
11
     * @param string|Builder $class
12
     * @param string $text
13
     * @param string $id
14
     * @param string|null $foreign
15
     * @return \Yajra\DataTables\Html\Editor\Fields\Field|static
16
     */
17
    public static function model($class, $text, $id = 'id', $foreign = null)
18
    {
19
        if ($class instanceof Builder) {
20
            $table = $class->getModel()->getTable();
0 ignored issues
show
Bug introduced by
The method getTable does only exist in Illuminate\Database\Eloquent\Model, but not in Illuminate\Database\Eloquent\Builder.

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...
21
        } else {
22
            $table = app($class)->getTable();
23
        }
24
25
        $table   = Str::singular($table);
26
        $foreign = $foreign ?? $table . '_id';
27
28
        return self::make($foreign, Str::title($table))
29
                   ->modelOptions($class, $text, $id);
30
    }
31
32
    /**
33
     * Add a placeholder and allow clear.
34
     * Note: This requires editor select2 plugin.
35
     *
36
     * @see https://editor.datatables.net/plug-ins/field-type/editor.select2
37
     * @param string $text
38
     * @param null|string $id
39
     * @param bool $allowClear
40
     * @return $this
41
     */
42
    public function placeholder($text, $id = null, $allowClear = true)
43
    {
44
        $this->type('select2')
45
             ->opts([
46
                 'allowClear'  => $allowClear,
47
                 'placeholder' => [
48
                     'id'   => $id,
49
                     'text' => $text,
50
                 ],
51
             ]);
52
53
        return $this;
54
    }
55
}
56