Completed
Branch devel (4fc3ef)
by Marcin
05:51
created

Sort::getIterator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
c 0
b 0
f 0
ccs 0
cts 2
cp 0
rs 10
cc 1
nc 1
nop 0
crap 2
1
<?php
2
/**
3
 * Created by Marcin.
4
 * Date: 16.06.2018
5
 * Time: 13:58
6
 */
7
8
namespace Mrcnpdlk\Lib\UrlSearchParser\Criteria;
9
10
use ArrayIterator;
11
use IteratorAggregate;
12
use Mrcnpdlk\Lib\UrlSearchParser\Exception\EmptyParamException;
13
use Traversable;
14
15
/**
16
 * Class Sort
17
 */
18
class Sort implements IteratorAggregate
19
{
20
    public const DIRECTION_ASC   = 'ASC';
21
    public const DIRECTION_DESC  = 'DESC';
22
    public const DELIMITER       = ',';
23
    public const DESC_IDENTIFIER = '-';
24
25
    /**
26
     * @var \Mrcnpdlk\Lib\UrlSearchParser\Criteria\SortParam[]
27
     */
28
    private $params = [];
29
30
    /**
31
     * Sort constructor.
32
     *
33
     * @param string|null $sortString
34
     *
35
     * @throws \Mrcnpdlk\Lib\UrlSearchParser\Exception\EmptyParamException
36
     */
37 20
    public function __construct(string $sortString = null)
38
    {
39
        /**
40
         * @var string[]
41
         * @var string   $param
42
         */
43 20
        $tParams = $sortString ? explode(self::DELIMITER, $sortString) : [];
44 20
        foreach ($tParams as $param) {
45 3
            if (empty($param)) {
46 1
                throw new EmptyParamException(sprintf('Empty SORT param'));
47
            }
48 2
            if (self::DESC_IDENTIFIER === $param[0]) {
49 2
                $param = substr($param, 1);
50 2
                if (empty($param)) {
51 1
                    throw new EmptyParamException(sprintf('Empty SORT param'));
52
                }
53 1
                $this->params[] = new SortParam($param, self::DIRECTION_DESC);
54
            } else {
55 1
                $this->params[] = new SortParam($param, self::DIRECTION_ASC);
56
            }
57
        }
58 18
    }
59
60
    /**
61
     * Retrieve an external iterator
62
     *
63
     * @see  http://php.net/manual/en/iteratoraggregate.getiterator.php
64
     *
65
     * @return Traversable An instance of an object implementing <b>Iterator</b> or
66
     *                     <b>Traversable</b>
67
     *
68
     * @since 5.0.0
69
     */
70
    public function getIterator(): Traversable
71
    {
72
        return new ArrayIterator($this->params);
73
    }
74
75
    /**
76
     * @return \Mrcnpdlk\Lib\UrlSearchParser\Criteria\SortParam[]
77
     */
78 2
    public function toArray(): array
79
    {
80 2
        return $this->params;
81
    }
82
}
83