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 — 1.1 ( cfead8...a57078 )
by Sebastian
04:23
created

DatabaseService::getAliases()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
ccs 0
cts 9
cp 0
rs 9.4286
cc 3
eloc 7
nc 3
nop 1
crap 12
1
<?php
2
3
namespace SebastianBerc\Repositories\Services;
4
5
use Illuminate\Contracts\Container\Container as Application;
6
use Illuminate\Database\Eloquent\Builder;
7
use Illuminate\Database\Eloquent\Collection;
8
use Illuminate\Database\Eloquent\Model as Eloquent;
9
use Illuminate\Pagination\LengthAwarePaginator;
10
use SebastianBerc\Repositories\Contracts\ServiceInterface;
11
use SebastianBerc\Repositories\Repository;
12
use SebastianBerc\Repositories\Traits\Filterable;
13
use SebastianBerc\Repositories\Traits\Sortable;
14
15
/**
16
 * Class DatabaseService.
17
 *
18
 * @author    Sebastian Berć <[email protected]>
19
 * @copyright Copyright (c) Sebastian Berć
20
 */
21
class DatabaseService implements ServiceInterface
22
{
23
    use Filterable, Sortable;
24
25
    /**
26
     * Contains Laravel Application instance.
27
     *
28
     * @var Application
29
     */
30
    protected $app;
31
32
    /**
33
     * Contains a repository instance.
34
     *
35
     * @var Repository
36
     */
37
    protected $repository;
38
39
    /**
40
     * Contains model instance for fetch, and simple fetch methods.
41
     *
42
     * @var mixed
43
     */
44
    protected $instance;
45
46
    /**
47
     * Create a new database service instance.
48
     *
49
     * @param Application $app
50
     * @param Repository  $repository
51
     */
52 120
    public function __construct(Application $app, Repository $repository)
53
    {
54 120
        $this->app        = $app;
55 120
        $this->repository = $repository;
56 120
    }
57
58
    /**
59
     * Get all of the models from the database.
60
     *
61
     * @param string[] $columns
62
     *
63
     * @return Collection
64
     */
65 12
    public function all(array $columns = ['*'])
66
    {
67 12
        return $this->repository->makeQuery()->get($columns);
68
    }
69
70
    /**
71
     * Create a new basic where query clause on model.
72
     *
73
     * @param string|array $column
74
     * @param string       $operator
75
     * @param mixed        $value
76
     * @param string       $boolean
77
     * @param string[]     $columns
78
     *
79
     * @return Collection
80
     */
81 20
    public function where($column, $operator = '=', $value = null, $boolean = 'and', array $columns = ['*'])
82
    {
83 20
        return $this->repository->makeQuery()->where($column, $operator, $value, $boolean, $columns)->get($columns);
84
    }
85
86
    /**
87
     * Paginate the given query.
88
     *
89
     * @param int      $perPage
90
     * @param string[] $columns
91
     *
92
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
93
     */
94 8
    public function paginate($perPage = 15, array $columns = ['*'])
95
    {
96 8
        return $this->repository->makeQuery()->paginate($perPage, $columns);
97
    }
98
99
    /**
100
     * Save a new model and return the instance.
101
     *
102
     * @param array $attributes
103
     *
104
     * @return Eloquent
105
     */
106 6
    public function create(array $attributes = [])
107
    {
108 6
        return $this->repository->makeModel()->create($attributes);
109
    }
110
111
    /**
112
     * Save or update the model in the database.
113
     *
114
     * @param mixed $identifier
115
     * @param array $attributes
116
     *
117
     * @return Eloquent
118
     */
119 6
    public function update($identifier, array $attributes = [])
120
    {
121
        $instance = $identifier instanceof Eloquent
122 6
            ? $identifier
123 6
            : $this->repository->makeQuery()->findOrFail($identifier);
124
125 6
        $instance->fill($attributes);
0 ignored issues
show
Bug introduced by
The method fill does only exist in Illuminate\Database\Eloquent\Model, but not in Illuminate\Database\Eloq...ase\Eloquent\Collection.

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...
126
127 6
        if ($instance->isDirty()) {
0 ignored issues
show
Bug introduced by
The method isDirty does only exist in Illuminate\Database\Eloquent\Model, but not in Illuminate\Database\Eloq...ase\Eloquent\Collection.

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...
128 6
            $instance->save();
0 ignored issues
show
Bug introduced by
The method save does only exist in Illuminate\Database\Eloquent\Model, but not in Illuminate\Database\Eloq...ase\Eloquent\Collection.

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...
129 6
        }
130
131 6
        return $instance;
132
    }
133
134
    /**
135
     * Delete the model from the database.
136
     *
137
     * @param int $identifier
138
     *
139
     * @return bool|null
140
     */
141 6
    public function delete($identifier)
142
    {
143 6
        return $this->repository->makeQuery()
0 ignored issues
show
Bug introduced by
The method delete does only exist in Illuminate\Database\Eloq...Database\Eloquent\Model, but not in Illuminate\Database\Eloquent\Collection.

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...
144 6
            ->findOrFail($identifier, [$this->repository->makeModel()->getKeyName()])
145 6
            ->delete();
146
    }
147
148
    /**
149
     * Find a model by its primary key.
150
     *
151
     * @param int      $identifier
152
     * @param string[] $columns
153
     *
154
     * @return Eloquent
155
     */
156 28
    public function find($identifier, array $columns = ['*'])
157
    {
158 28
        return $this->repository->makeQuery()->find($identifier, $columns);
159
    }
160
161
    /**
162
     * Find a model by its specified column and value.
163
     *
164
     * @param mixed    $column
165
     * @param mixed    $value
166
     * @param string[] $columns
167
     *
168
     * @return Eloquent
169
     */
170 8
    public function findBy($column, $value, array $columns = ['*'])
171
    {
172 8
        return $this->where([$column => $value], '=', null, 'and', $columns)->first();
173
    }
174
175
    /**
176
     * Find a model by its specified columns and values presented as array.
177
     *
178
     * @param array    $wheres
179
     * @param string[] $columns
180
     *
181
     * @return Eloquent
182
     */
183 8
    public function findWhere(array $wheres, array $columns = ['*'])
184
    {
185 8
        return $this->where($wheres, '=', null, 'and', $columns)->first();
186
    }
187
188
    /**
189
     * Find a models by its primary key.
190
     *
191
     * @param array    $identifiers
192
     * @param string[] $columns
193
     *
194
     * @return Collection
195
     */
196
    public function findMany($identifiers, array $columns = ['*'])
197
    {
198
        return $this->repository->makeQuery()->findMany($identifiers, $columns);
199
    }
200
201
    /**
202
     * Search the models in search of words in a given phrase to the specified columns.
203
     *
204
     * @param string $search
205
     * @param array  $columns
206
     * @param float  $threshold
207
     *
208
     * @return Builder
209
     */
210
    public function search($search, array $columns = [], $threshold = null)
211
    {
212
        $searchable = empty($columns) ? $columns : $this->repository->getSearchableFields();
213
        $service    = new SearchService($this->repository->makeQuery(), $searchable, $threshold);
214
215
        return $service->search($search);
216
    }
217
218
    /**
219
     * Returns total count of whole collection.
220
     *
221
     * @return int
222
     */
223 4
    public function count()
224
    {
225 4
        $countBy = "{$this->repository->makeModel()->getTable()}.{$this->repository->makeModel()->getKeyName()}";
226
227 4
        return $this->repository->makeQuery()->count($countBy);
228
    }
229
230
    /**
231
     * Fetch collection ordered and filtrated by specified columns for specified page as paginator.
232
     *
233
     * @param int    $page
234
     * @param int    $perPage
235
     * @param array  $columns
236
     * @param array  $filter
237
     * @param array  $sort
238
     * @param string $search
239
     *
240
     * @return LengthAwarePaginator
241
     */
242 12
    public function fetch(
243
        $page = 1,
244
        $perPage = 15,
245
        array $columns = ['*'],
246
        array $filter = [],
247
        array $sort = [],
248
        $search = null
249
    ) {
250 12 View Code Duplication
        if (empty($search)) {
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...
251 12
            $this->instance = $this->parseAliases($this->repository->makeQuery());
252 12
            $this->multiFilterBy($filter)->multiSortBy($sort);
253 12
        } else {
254
            $this->instance = $this->repository->search($search);
255 2
        }
256
257 12
        $count = $this->countResults($this->instance);
258 12
        $items = $this->instance->forPage($page, $perPage)->get($columns);
259
260
        $options = [
261 12
            'path'  => $this->app->make('request')->url(),
262 12
            'query' => compact('page', 'perPage'),
263 12
        ];
264
265 12
        return (new LengthAwarePaginator($items, $count, $perPage, $page, $options));
266
    }
267
268
    /**
269
     * Fetch collection ordered and filtrated by specified columns for specified page.
270
     *
271
     * @param int    $page
272
     * @param int    $perPage
273
     * @param array  $columns
274
     * @param array  $filter
275
     * @param array  $sort
276
     * @param string $search
277
     *
278
     * @return Collection
279
     */
280 4
    public function simpleFetch(
281
        $page = 1,
282
        $perPage = 15,
283
        array $columns = ['*'],
284
        array $filter = [],
285
        array $sort = [],
286
        $search = null
287
    ) {
288 4 View Code Duplication
        if (is_null($search)) {
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...
289 4
            $this->instance = $this->parseAliases($this->repository->makeQuery());
290 4
            $this->multiFilterBy($filter)->multiSortBy($sort);
291 4
        } else {
292
            $this->instance = $this->repository->search($search);
293
        }
294
295 4
        return $this->instance->forPage($page, $perPage)->get($columns);
296
    }
297
298
    /**
299
     * Replace alias name in where closure with sub-queries from select.
300
     *
301
     * Example:
302
     *
303
     * SELECT table.*, (SELECT 1 FROM other_table ot WHERE ot.id = table.id) AS exists
304
     * WHERE exists = 1;
305
     *
306
     * Will be converted to:
307
     *
308
     * SELECT table.*, (SELECT 1 FROM other_table ot WHERE ot.id = table.id) AS exists
309
     * WHERE (SELECT 1 FROM other_table ot WHERE ot.id = table.id) = 1;
310
     *
311
     * @param Builder $query
312
     *
313
     * @return Builder
314
     */
315 16
    protected function parseAliases(Builder $query)
316
    {
317 16
        $aliases = [];
318
319 16
        if (!empty($query->getQuery()->columns)) {
320
            $aliases = $this->getAliases($query);
321
        }
322
323 16
        if (!empty($aliases) & !empty($query->getQuery()->wheres)) {
324
            $this->replaceAliases($query, $aliases);
325
        }
326
327 16
        return $query;
328
    }
329
330
    /**
331
     * Counts results for given query.
332
     *
333
     * @param Builder $query
334
     *
335
     * @return int
336
     */
337 12
    protected function countResults(Builder $query)
338
    {
339 12
        $query = clone $query;
340
341 12
        $query->getQuery()->aggregate = ['function' => 'count', 'columns' => $columns = ['*']];
342 12
        $query->getQuery()->orders    = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $orders.

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...
343
344 12
        $results = $query->getQuery()->get($columns);
345
346 12
        if (isset($results[0])) {
347 12
            return array_change_key_case((array) $results[0])['aggregate'];
348
        }
349
    }
350
351
    /**
352
     * Get sub queries and aliases from select statement.
353
     *
354
     * @param Builder $query
355
     *
356
     * @return array
357
     */
358
    protected function getAliases(Builder $query)
359
    {
360
        $aliases = [];
361
362
        foreach ($query->getQuery()->columns as $column) {
363
            if (preg_match("~AS (\w+)~i", $column, $matches)) {
364
                $aliases[$query->getModel()->getTable() . '.' . $matches[1]]
365
                    = \DB::raw(str_replace($matches[0], '', $column));
366
            }
367
        }
368
369
        return $aliases;
370
    }
371
372
    /**
373
     * Replace aliases in where statement with sub queries.
374
     *
375
     * @param Builder $query
376
     * @param array   $aliases
377
     *
378
     * @return void
379
     */
380
    protected function replaceAliases(Builder $query, $aliases)
381
    {
382
        foreach ($query->getQuery()->wheres as $key => $value) {
383
            if (in_array($value['column'], array_keys($aliases))) {
384
                $query->getQuery()->wheres[$key]['column'] = $aliases[$value['column']];
385
            }
386
        }
387
    }
388
}
389