Completed
Push — master ( eca780...57807c )
by Alejandro
27s queued 11s
created

ShortUrlsOrdering::validateAndInit()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 7.392

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 9
c 1
b 0
f 0
nc 6
nop 1
dl 0
loc 17
rs 8.8333
ccs 8
cts 10
cp 0.8
crap 7.392
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Shlinkio\Shlink\Core\Model;
6
7
use Shlinkio\Shlink\Core\Exception\ValidationException;
8
9
use function is_array;
10
use function is_string;
11
use function key;
12
13
final class ShortUrlsOrdering
14
{
15
    public const ORDER_BY = 'orderBy';
16
    private const DEFAULT_ORDER_DIRECTION = 'ASC';
17
18
    private ?string $orderField = null;
19
    private string $orderDirection = self::DEFAULT_ORDER_DIRECTION;
20
21
    /**
22
     * @throws ValidationException
23
     */
24 49
    public static function fromRawData(array $query): self
25
    {
26 49
        $instance = new self();
27 49
        $instance->validateAndInit($query);
28
29 49
        return $instance;
30
    }
31
32
    /**
33
     * @throws ValidationException
34
     */
35 49
    private function validateAndInit(array $data): void
36
    {
37
        /** @var string|array|null $orderBy */
38 49
        $orderBy = $data[self::ORDER_BY] ?? null;
39 49
        if ($orderBy === null) {
40 39
            return;
41
        }
42
43 10
        $isArray = is_array($orderBy);
44 10
        if (! $isArray && $orderBy !== null && ! is_string($orderBy)) {
0 ignored issues
show
introduced by
The condition is_string($orderBy) is always true.
Loading history...
45
            throw ValidationException::fromArray([
46
                'orderBy' => '"Order by" must be an array, string or null',
47
            ]);
48
        }
49
50 10
        $this->orderField = $isArray ? key($orderBy) : $orderBy;
0 ignored issues
show
Bug introduced by
It seems like $orderBy can also be of type string; however, parameter $array of key() 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

50
        $this->orderField = $isArray ? key(/** @scrutinizer ignore-type */ $orderBy) : $orderBy;
Loading history...
51 10
        $this->orderDirection = $isArray ? $orderBy[$this->orderField] : self::DEFAULT_ORDER_DIRECTION;
52
    }
53
54
    public function orderField(): ?string
55
    {
56
        return $this->orderField;
57
    }
58
59
    public function orderDirection(): string
60
    {
61
        return $this->orderDirection;
62
    }
63
64
    public function hasOrderField(): bool
65
    {
66
        return $this->orderField !== null;
67
    }
68
}
69