|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Jackal\Copycat\Sorter\ValueSorter; |
|
4
|
|
|
|
|
5
|
|
|
use Jackal\Copycat\Sorter\SorterInterface; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Class AscendingSorter |
|
9
|
|
|
* @package Jackal\Copycat\Sorter\ValueSorter |
|
10
|
|
|
*/ |
|
11
|
|
|
class AscendingSorter implements SorterInterface |
|
12
|
|
|
{ |
|
13
|
|
|
/** |
|
14
|
|
|
* @var array |
|
15
|
|
|
*/ |
|
16
|
|
|
protected $fieldNames; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* @return int |
|
20
|
|
|
*/ |
|
21
|
|
|
protected function getOrder() |
|
22
|
|
|
{ |
|
23
|
|
|
return SORT_ASC; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* AscendingSorter constructor. |
|
28
|
|
|
* @param mixed ...$fieldName |
|
29
|
|
|
*/ |
|
30
|
|
|
public function __construct(...$fieldName) |
|
31
|
|
|
{ |
|
32
|
|
|
$this->fieldNames = func_get_args(); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* @param $values |
|
37
|
|
|
* @return array|mixed |
|
38
|
|
|
*/ |
|
39
|
|
|
public function __invoke(&$values) |
|
40
|
|
|
{ |
|
41
|
|
|
$orderColumns = []; |
|
42
|
|
|
foreach ($this->fieldNames as $fieldName) { |
|
43
|
|
|
$orderColumns[$fieldName] = $this->getOrder(); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
$values = array_values($this->array_mSort($values, $orderColumns)); |
|
47
|
|
|
|
|
48
|
|
|
return $values; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* @param $array |
|
53
|
|
|
* @param $cols |
|
54
|
|
|
* @return array |
|
55
|
|
|
* Taken from https://www.php.net/manual/en/function.array-multisort.php |
|
56
|
|
|
*/ |
|
57
|
|
|
private function array_mSort($array, $cols) |
|
58
|
|
|
{ |
|
59
|
|
|
$colArr = []; |
|
60
|
|
|
foreach ($cols as $col => $order) { |
|
61
|
|
|
$colArr[$col] = []; |
|
62
|
|
|
foreach ($array as $k => $row) { |
|
63
|
|
|
$colArr[$col]['_' . $k] = strtolower($row[$col]); |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
/** @noinspection SpellCheckingInspection */ |
|
67
|
|
|
$eval = 'array_multisort('; |
|
68
|
|
|
foreach ($cols as $col => $order) { |
|
69
|
|
|
$eval .= '$colArr[\'' . $col . '\'],' . $order . ','; |
|
70
|
|
|
} |
|
71
|
|
|
$eval = substr($eval, 0, -1) . ');'; |
|
72
|
|
|
eval($eval); |
|
|
|
|
|
|
73
|
|
|
$ret = []; |
|
74
|
|
|
foreach ($colArr as $col => $arr) { |
|
75
|
|
|
foreach ($arr as $k => $v) { |
|
76
|
|
|
$k = substr($k, 1); |
|
77
|
|
|
if (!isset($ret[$k])) { |
|
78
|
|
|
$ret[$k] = $array[$k]; |
|
79
|
|
|
} |
|
80
|
|
|
$ret[$k][$col] = $array[$k][$col]; |
|
81
|
|
|
} |
|
82
|
|
|
} |
|
83
|
|
|
|
|
84
|
|
|
return $ret; |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|