Completed
Push — master ( 3df620...302649 )
by Jesse
13:06
created

OrderByParser::allowing()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\Sorting;
4
5
use function array_combine;
6
use function array_key_exists;
7
use function implode;
8
use InvalidArgumentException;
9
use function sprintf;
10
use Stratadox\Sorting\Contracts\Sorting;
11
12
class OrderByParser
13
{
14
    /** @var array */
15
    private $sortableFields;
16
17
    private function __construct(array $sortableFields = [])
18
    {
19
        $this->sortableFields = $sortableFields;
20
    }
21
22
    public static function mappedAs(array $sortableFieldsMap): self
23
    {
24
        return new self($sortableFieldsMap);
25
    }
26
27
    public static function allowing(string ...$sortableFields): self
28
    {
29
        return new self(array_combine($sortableFields, $sortableFields));
0 ignored issues
show
Bug introduced by
It seems like array_combine($sortableFields, $sortableFields) can also be of type false; however, parameter $sortableFields of Stratadox\Sorting\OrderByParser::__construct() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

29
        return new self(/** @scrutinizer ignore-type */ array_combine($sortableFields, $sortableFields));
Loading history...
30
    }
31
32
    public function parse(Sorting $sorting): string
33
    {
34
        if (!$sorting->isRequired()) {
35
            return '';
36
        }
37
        $orderBy = [];
38
        while ($sorting->isRequired()) {
39
            $orderBy[] = $this->parseSingle($sorting);
40
            $sorting = $sorting->next();
41
        }
42
        return sprintf('ORDER BY %s', implode(', ', $orderBy));
43
    }
44
45
    private function parseSingle(Sorting $sorting): string
46
    {
47
        if (!array_key_exists($sorting->field(), $this->sortableFields)) {
48
            throw new InvalidArgumentException(
49
                $sorting->field() . ' is not a sortable field.'
50
            );
51
        }
52
        return sprintf(
53
            '%s %s',
54
            $this->sortableFields[$sorting->field()],
55
            $sorting->ascends() ? 'ASC' : 'DESC'
56
        );
57
    }
58
}
59