1
|
|
|
<?php |
2
|
|
|
namespace EngineWorks\Pivot; |
3
|
|
|
|
4
|
|
|
/** |
5
|
|
|
* Class to sort elements (ordering) of a result |
6
|
|
|
*/ |
7
|
|
|
class ResultOrdering |
8
|
|
|
{ |
9
|
|
|
/** @var array */ |
10
|
|
|
private $orderBy; |
11
|
|
|
|
12
|
|
|
/** @var bool */ |
13
|
|
|
private $required; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* ResultOrdering constructor |
17
|
|
|
* The parameter orderBy must contain the list of aggregates and the order they must use |
18
|
|
|
* [$aggregate1 => $order1, $aggregate2 => $order2, ... ] |
19
|
|
|
* |
20
|
|
|
* @param array $orderBy |
21
|
|
|
*/ |
22
|
9 |
|
public function __construct(array $orderBy) |
23
|
|
|
{ |
24
|
9 |
|
$this->orderBy = $orderBy; |
25
|
9 |
|
$this->required = false; |
26
|
9 |
|
foreach ($orderBy as $criteria) { |
27
|
9 |
|
if ($criteria) { |
28
|
4 |
|
$this->required = true; |
29
|
9 |
|
break; |
30
|
|
|
} |
31
|
|
|
} |
32
|
9 |
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Method to make comparisons |
36
|
|
|
* |
37
|
|
|
* @param Result $a |
38
|
|
|
* @param Result $b |
39
|
|
|
* @return int |
40
|
|
|
*/ |
41
|
3 |
|
public function orderItems(Result $a, Result $b) |
42
|
|
|
{ |
43
|
|
|
// compare using every aggregator with its own order type |
44
|
3 |
|
foreach ($this->orderBy as $field => $order) { |
45
|
3 |
|
if ($order === Aggregate::ORDERASC) { |
46
|
|
|
return $this->comparePivotValues($field, $a, $b); |
47
|
3 |
|
} elseif ($order === Aggregate::ORDERDESC) { |
48
|
3 |
|
return $this->comparePivotValues($field, $b, $a); |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
// if $a and $b are the same, order alphabetically by caption |
52
|
|
|
return strcasecmp($a->caption, $b->caption); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Return if ordering is required based on the orderBy array |
57
|
|
|
* |
58
|
|
|
* @return bool |
59
|
|
|
*/ |
60
|
9 |
|
public function isRequired() |
61
|
|
|
{ |
62
|
9 |
|
return $this->required; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* Internal method to check two numerical values and return 0, -1 or 1 |
67
|
|
|
* |
68
|
|
|
* @param string $field |
69
|
|
|
* @param Result $a |
70
|
|
|
* @param Result $b |
71
|
|
|
* @return int |
72
|
|
|
*/ |
73
|
3 |
|
protected function comparePivotValues($field, Result $a, Result $b) |
74
|
|
|
{ |
75
|
3 |
|
return $a->values[$field] <=> $b->values[$field]; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|