AscendingSorter::array_mSort()   B
last analyzed

Complexity

Conditions 7
Paths 24

Size

Total Lines 28
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 18
c 0
b 0
f 0
dl 0
loc 28
rs 8.8333
cc 7
nc 24
nop 2
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);
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
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