AscendingSorter   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 2
Metric Value
wmc 11
eloc 27
c 2
b 0
f 2
dl 0
loc 74
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getOrder() 0 3 1
A __construct() 0 3 1
B array_mSort() 0 28 7
A __invoke() 0 10 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