GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( b864c9...ed9166 )
by butschster
12:41
created

SelectOptionsFromModel::loadOptions()   B

Complexity

Conditions 9
Paths 48

Size

Total Lines 55
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 0
Metric Value
cc 9
eloc 28
nc 48
nop 0
dl 0
loc 55
ccs 0
cts 34
cp 0
crap 90
rs 7.2446
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace SleepingOwl\Admin\Traits;
4
5
use Illuminate\Support\Collection;
6
use Illuminate\Database\Eloquent\Model;
7
use SleepingOwl\Admin\Exceptions\Form\Element\SelectException;
8
use SleepingOwl\Admin\Contracts\Repositories\RepositoryInterface;
9
10
trait SelectOptionsFromModel
11
{
12
    /**
13
     * @var Model
14
     */
15
    protected $modelForOptions;
16
17
    /**
18
     * @var string
19
     */
20
    protected $display = 'title';
21
22
    /**
23
     * @var string|null
24
     */
25
    protected $foreignKey = null;
26
27
    /**
28
     * @var array
29
     */
30
    protected $fetchColumns = [];
31
32
    /**
33
     * @var \Closure|object callable
34
     */
35
    protected $loadOptionsQueryPreparer;
36
37
    /**
38
     * @var bool
39
     */
40
    protected $isEmptyRelation = false;
41
42
    /**
43
     * @return Model
44
     */
45
    public function getModelForOptions()
46
    {
47
        return $this->modelForOptions;
48
    }
49
50
    /**
51
     * @param @param string|Model $modelForOptions
52
     *
53
     * @return $this
54
     * @throws SelectException
55
     */
56
    public function setModelForOptions($modelForOptions)
57
    {
58
        if (is_string($modelForOptions)) {
59
            $modelForOptions = app($modelForOptions);
60
        }
61
62
        if (! ($modelForOptions instanceof Model)) {
63
            throw new SelectException('Class must be instanced of Illuminate\Database\Eloquent\Model');
64
        }
65
66
        $this->modelForOptions = $modelForOptions;
67
68
        return $this;
69
    }
70
71
    /**
72
     * @return string
73
     */
74
    public function getDisplay()
75
    {
76
        return $this->display;
77
    }
78
79
    /**
80
     * @param string $display
81
     *
82
     * @return $this
83
     */
84
    public function setDisplay($display)
85
    {
86
        $this->display = $display;
87
88
        return $this;
89
    }
90
91
    /**
92
     * Set Only fetch columns.
93
     *
94
     * If use {@link Select#setModelForOptions($model)}, on fetch
95
     * data from the $model table, only specified columns has be
96
     * feched.
97
     *
98
     * Examples: <code>setFetchColumns('title')</code> or
99
     * <code>setFetchColumns(['title'])</code> or
100
     * <code>setFetchColumns('title', 'position')</code> or
101
     * <code>setFetchColumns(['title', 'position'])</code>.
102
     *
103
     * @param string|array $columns
104
     * @return $this
105
     */
106
    public function setFetchColumns($columns)
107
    {
108
        if (! is_array($columns)) {
109
            $columns = func_get_args();
110
        }
111
112
        $this->fetchColumns = $columns;
113
114
        return $this;
115
    }
116
117
    /**
118
     * Get the fetch columns.
119
     *
120
     * @return array
121
     */
122
    public function getFetchColumns()
123
    {
124
        return $this->fetchColumns;
125
    }
126
127
    /**
128
     * Set Callback for prepare load options Query.
129
     *
130
     * Example:
131
     * <code>
132
     * <?php
133
     * AdminFormElement::select('column', 'Label')
134
     *     ->modelForOptions(MyModel::class)
135
     *     ->setLoadOptionsQueryPreparer(function($item, QueryBuilder $query) {
136
     *         return $query
137
     *             ->where('column', 'value')
138
     *             ->were('owner_id', Auth::user()->id)
139
     *     });
140
     * ?>
141
     * </code>
142
     *
143
     * @param callable $callback The Callback with $item and $options args.
144
     * @return $this
145
     */
146
    public function setLoadOptionsQueryPreparer($callback)
147
    {
148
        $this->loadOptionsQueryPreparer = $callback;
0 ignored issues
show
Documentation Bug introduced by
It seems like $callback of type callable is incompatible with the declared type object of property $loadOptionsQueryPreparer.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
149
150
        return $this;
151
    }
152
153
    /**
154
     * Get Callback for prepare load options Query.
155
     * @return callable
156
     */
157
    public function getLoadOptionsQueryPreparer()
158
    {
159
        return $this->loadOptionsQueryPreparer;
160
    }
161
162
    /**
163
     * @param null|string $foreignKey
164
     *
165
     * @return $this
166
     */
167
    public function setForeignKey($foreignKey)
168
    {
169
        $this->foreignKey = $foreignKey;
170
171
        return $this;
172
    }
173
174
    /**
175
     * @return $this
176
     */
177
    public function onlyEmptyRelation()
178
    {
179
        $this->isEmptyRelation = true;
180
181
        return $this;
182
    }
183
184
    /**
185
     * @return bool
186
     */
187
    public function isEmptyRelation()
188
    {
189
        return $this->isEmptyRelation;
190
    }
191
192
    /**
193
     * @return array
194
     */
195
    protected function loadOptions()
196
    {
197
        $repository = app(RepositoryInterface::class);
198
        $repository->setModel($this->getModelForOptions());
199
        $key = $repository->getModel()->getKeyName();
200
201
        $options = $repository->getQuery();
202
203
        if ($this->isEmptyRelation() and ! is_null($foreignKey = $this->getForeignKey())) {
0 ignored issues
show
Bug introduced by
It seems like getForeignKey() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
204
            $relation = $this->getModelAttributeKey();
0 ignored issues
show
Bug introduced by
It seems like getModelAttributeKey() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
205
            $model = $this->getModel();
0 ignored issues
show
Bug introduced by
The method getModel() does not exist on SleepingOwl\Admin\Traits\SelectOptionsFromModel. Did you maybe mean getModelForOptions()?

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...
206
207
            if ($model->{$relation}() instanceof HasOneOrMany) {
0 ignored issues
show
Bug introduced by
The class SleepingOwl\Admin\Traits\HasOneOrMany does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
208
                $options->where($foreignKey, 0)->orWhereNull($foreignKey);
209
            }
210
        }
211
212
        if (count($this->getFetchColumns()) > 0) {
213
            $options->select(
214
                array_merge([$key], $this->getFetchColumns())
215
            );
216
        }
217
218
        // call the pre load options query preparer if has be set
219
        if (! is_null($preparer = $this->getLoadOptionsQueryPreparer())) {
220
            $options = $preparer($this, $options);
221
        }
222
223
        $options = $options->get();
224
225
        if (is_callable($makeDisplay = $this->getDisplay())) {
226
            // make dynamic display text
227
            if ($options instanceof Collection) {
228
                $options = $options->all();
229
            }
230
231
            // iterate for all options and redefine it as
232
            // list of KEY and TEXT pair
233
            $options = array_map(function ($opt) use ($key, $makeDisplay) {
234
                // get the KEY and make the display text
235
                return [data_get($opt, $key), $makeDisplay($opt)];
236
            }, $options);
237
238
            // take options as array with KEY => VALUE pair
239
            $options = array_pluck($options, 1, 0);
240
        } elseif ($options instanceof Collection) {
241
            // take options as array with KEY => VALUE pair
242
            $options = array_pluck($options->all(), $this->getDisplay(), $key);
243
        } else {
244
            // take options as array with KEY => VALUE pair
245
            $options = array_pluck($options, $this->getDisplay(), $key);
246
        }
247
248
        return $options;
249
    }
250
}
251