EloquentDataProvider::getCount()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Itstructure\GridView\DataProviders;
4
5
use Illuminate\Http\Request;
6
use Illuminate\Support\Collection;
7
use Illuminate\Database\Eloquent\Builder;
8
use Itstructure\GridView\Grid;
9
use Itstructure\GridView\Helpers\SortHelper;
10
11
/**
12
 * Class EloquentDataProvider.
13
 * @package Itstructure\GridView\DataProviders
14
 */
15
class EloquentDataProvider extends BaseDataProvider
16
{
17
    /**
18
     * @var Builder
19
     */
20
    protected $query;
21
22
    /**
23
     * EloquentDataProvider constructor.
24
     * @param Builder $query
25
     */
26
    public function __construct(Builder $query)
27
    {
28
        $this->query = clone $query;
29
    }
30
31
    /**
32
     * @param int $perPage
33
     * @param int $page
34
     * @return Collection
35
     */
36
    public function get(int $perPage = Grid::INIT_ROWS_PER_PAGE, int $page = Grid::INIT_PAGE_NUMBER): Collection
37
    {
38
        return $this->query->offset(($page - 1) * $perPage)->limit($perPage)->get() ?? new Collection();
39
    }
40
41
    /**
42
     * @param Request $request
43
     * @param bool $strictFilters
44
     * @return void
45
     */
46
    public function selectionConditions(Request $request, bool $strictFilters = false): void
47
    {
48
        if ($request->get('sort', null)) {
49
            $this->query->orderBy(SortHelper::getSortColumn($request), SortHelper::getDirection($request));
50
        }
51
52
        if (!is_null($request->filters)) {
53
            foreach ($request->filters as $column => $value) {
54
                if (is_null($value)) {
55
                    continue;
56
                }
57
58
                if ($strictFilters) {
59
                    $this->query->where($column, '=', $value);
60
                } else {
61
                    $this->query->where($column, 'like', '%' . $value . '%');
62
                }
63
            }
64
        }
65
    }
66
67
    /**
68
     * @return int
69
     */
70
    public function getCount(): int
71
    {
72
        return $this->query->count();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->query->count() could return the type Illuminate\Database\Eloquent\Builder which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
73
    }
74
}
75