RequestResourceContext::toArray()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 10
nc 1
nop 1
dl 0
loc 12
ccs 10
cts 10
cp 1
crap 1
rs 9.9332
c 1
b 0
f 1
1
<?php
2
3
namespace Mblarsen\LaravelRepository;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Http\Request;
7
use Illuminate\Support\Arr;
8
9
class RequestResourceContext implements ResourceContext
10
{
11
    /** @var Request */
12
    protected $request;
13
14
    /** @var array */
15
    protected $keys = [
16
        'filters' => 'filters',
17
        'page' => 'page',
18
        'per_page' => 'per_page',
19
        'sort_by' => 'sort_by',
20
        'sort_order' => 'sort_order',
21
        'with' => 'with',
22
    ];
23
24 64
    public function __construct()
25
    {
26 64
        $this->request = request();
27 64
    }
28
29 16
    public function filters(): array
30
    {
31 16
        return $this->get('filters', []);
32
    }
33
34 12
    public function page(): int
35
    {
36 12
        return $this->get('page', 1);
37
    }
38
39 12
    public function perPage(): int
40
    {
41 12
        return $this->get('per_page', 15);
42
    }
43
44 15
    public function paginate(): bool
45
    {
46 15
        return $this->has('page');
47
    }
48
49 16
    public function sortBy(): array
50
    {
51
        return [
52 16
            $this->get('sort_by', null),
53 16
            $this->get('sort_order', null),
54
        ];
55
    }
56
57 3
    public function user($guard = null): ?Model
58
    {
59 3
        return $this->request->user($guard);
60
    }
61
62 18
    public function with(): array
63
    {
64 18
        return $this->has('with')
65 3
            ? Arr::wrap($this->get('with'))
66 18
            : [];
67
    }
68
69 1
    public function mapKeys(array $keys)
70
    {
71 1
        $this->keys = array_merge($this->keys, $keys);
72
73 1
        return $this;
74
    }
75
76
    /**
77
     * @inheritdoc
78
     */
79 3
    public function toArray($guard = null): array
80
    {
81 3
        [$sort_by, $sort_order] = $this->sortBy();
82
        return [
83 3
            'filters' => $this->filters(),
84 3
            'page' => $this->get('page'),
85 3
            'paginate' => $this->paginate(),
86 3
            'per_page' => $this->get('per_page'),
87 3
            'sort_by' => $sort_by,
88 3
            'sort_order' => $sort_order,
89 3
            'user' => $this->user($guard),
90 3
            'with' => $this->with(),
91
        ];
92
    }
93
94 18
    protected function has($key)
95
    {
96 18
        return $this->request->has($this->keys[$key]);
97
    }
98
99 16
    protected function get($key, $default = null)
100
    {
101 16
        return $this->request->get($this->keys[$key], $default);
102
    }
103
}
104