Sorts::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 10
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 16
ccs 9
cts 9
cp 1
crap 2
rs 9.9332
1
<?php
2
3
declare(strict_types=1);
4
5
namespace ApiChef\RequestQueryHelper;
6
7
use Illuminate\Support\Collection;
8
use Illuminate\Support\Str;
9
10
class Sorts
11
{
12
    private Collection $fields;
13
14
    /**
15
     * @param null|string|array $sorts
16 6
     */
17
    public function __construct($sorts = null)
18 6
    {
19
        $this->fields = Collection::make();
20 6
        $sorts = (new QueryParamBag($sorts))->getParams();
21
        $fields = array_keys($sorts);
22
23 6
        collect($fields)->each(function (string $field) use ($sorts) {
24
            $params = $sorts[$field];
25 6
            $direction = SortField::DIRECTION_ASCENDING;
26 6
27 6
            if (Str::startsWith($field, '-')) {
28
                $direction = SortField::DIRECTION_DESCENDING;
29
                $field = Str::after($field, '-');
30 6
            }
31 6
32 6
            $this->fields->push(new SortField($field, $direction, $params));
33
        });
34 3
    }
35
36 3
    public function getFields(): Collection
37
    {
38
        return $this->fields;
39 3
    }
40
}
41