OrderBy::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace Puzzle\QueryBuilder\Queries\Snippets;
6
7
use Puzzle\QueryBuilder\Snippet;
8
9
class OrderBy implements Snippet
10
{
11
    const
12
        ASC = 'ASC',
13
        DESC = 'DESC';
14
15
    private
16
        $orders;
1 ignored issue
show
Coding Style introduced by
The visibility should be declared for property $orders.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
17
18 45
    public function __construct()
19
    {
20 45
        $this->orders = array();
21 45
    }
22
23 13
    public function addOrderBy(string $column, string $direction = self::ASC): void
24
    {
25 13
        $this->validateDirection($direction);
26
27 12
        $this->orders[$column] = $direction;
28 12
    }
29
30 38
    public function toString(): string
31
    {
32 38
        $orders = [];
33
34 38
        foreach($this->orders as $column => $direction)
35
        {
36 12
            if(! empty($column))
37
            {
38 11
                $orders[] = $column . ' ' . $direction;
39
            }
40
        }
41
42 38
        if(empty($orders))
43
        {
44 29
            return '';
45
        }
46
47 11
        return sprintf('ORDER BY %s', implode(', ', $orders));
48
    }
49
50 13
    private function validateDirection(string $direction): void
51
    {
52 13
        $availableDirections = [self::ASC, self::DESC];
53
54 13
        if(! in_array($direction, $availableDirections))
55
        {
56 1
            throw new \InvalidArgumentException(sprintf('Unsupported ORDER BY direction "%s"', $direction));
57
        }
58 12
    }
59
}
60