Passed
Pull Request — master (#648)
by John
06:48
created

ApiController::users()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 8
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 12
rs 10
1
<?php
2
3
namespace App\Admin\Controllers;
4
5
use App\Models\Eloquent\User;
6
use App\Models\Eloquent\Problem;
7
use Encore\Admin\Controllers\AdminController;
8
use Illuminate\Pagination\Paginator;
9
use Illuminate\Pagination\LengthAwarePaginator;
10
11
class ApiController extends AdminController
12
{
13
    protected function paginate($items, $perPage = 15, $pageStart = 1)
14
    {
15
        $offSet = ($pageStart * $perPage) - $perPage;
16
        $itemsForCurrentPage = array_slice($items, $offSet, $perPage, true);
17
        $paginator = new LengthAwarePaginator($itemsForCurrentPage, count($items), $perPage, Paginator::resolveCurrentPage(), ['path' => Paginator::resolveCurrentPath()]);
18
        return $paginator;
19
    }
20
21
    public function problems()
22
    {
23
        $q = request()->q;
24
25
        return $this->paginate(Problem::orderBy('pcode', 'asc')->get()->filter(function ($problem) use ($q) {
26
            return stripos($problem->readable_name, $q) !== false;
27
        })->values()->transform(function ($problem) {
28
            return [
29
                'id' => $problem->pid,
30
                'text' => $problem->readable_name,
31
            ];
32
        })->toArray());
33
    }
34
35
    public function users()
36
    {
37
        $q = request()->q;
38
39
        return $this->paginate(User::get()->filter(function ($user) use ($q) {
40
            return stripos($user->readable_name, $q) !== false;
41
        })->values()->transform(function ($user) {
42
            return [
43
                'id' => $user->id,
44
                'text' => $user->readable_name,
45
            ];
46
        })->toArray());
47
    }
48
}
49