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