SortedIterator::__construct()   B
last analyzed

Complexity

Conditions 7
Paths 4

Size

Total Lines 25

Duplication

Lines 10
Ratio 40 %

Code Coverage

Tests 17
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
nc 4
nop 3
dl 10
loc 25
ccs 17
cts 17
cp 1
crap 7
rs 8.5866
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Zicht Online <http://zicht.nl>
4
 */
5
6
namespace Zicht\Itertools\lib;
7
8
use Zicht\Itertools\lib\Interfaces\FiniteIterableInterface;
9
use Zicht\Itertools\lib\Traits\FiniteIterableTrait;
10
11
class SortedIterator extends \IteratorIterator implements FiniteIterableInterface
12
{
13
    use FiniteIterableTrait;
14
15
    /**
16
     * @param \Closure $func
17
     * @param \Iterator $iterable
18
     * @param bool $reverse
19
     */
20 37
    public function __construct(\Closure $func, \Iterator $iterable, $reverse = false)
21
    {
22 37
        if ($reverse) {
23 View Code Duplication
            $cmp = function ($a, $b) use ($func) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
24 2
                $orderA = $a['order'];
25 2
                $orderB = $b['order'];
26 2
                return $orderA == $orderB ? 0 : ($orderA < $orderB ? 1 : -1);
27 2
            };
28
        } else {
29 35 View Code Duplication
            $cmp = function ($a, $b) use ($func) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
30 35
                $orderA = $a['order'];
31 35
                $orderB = $b['order'];
32 35
                return $orderA == $orderB ? 0 : ($orderA < $orderB ? -1 : 1);
33 35
            };
34
        }
35
36 37
        $data = [];
37 37
        foreach ($iterable as $key => $value) {
38 37
            $data [] = ['key' => $key, 'value' => $value, 'order' => call_user_func($func, $value, $key)];
39
        }
40
41 37
        $this->mergeSort($data, $cmp);
42
43 37
        parent::__construct(new \ArrayIterator($data));
44 37
    }
45
46
    /**
47
     * {@inheritDoc}
48
     */
49 35
    public function key()
50
    {
51 35
        return $this->getInnerIterator()->current()['key'];
52
    }
53
54
    /**
55
     * {@inheritDoc}
56
     */
57 35
    public function current()
58
    {
59 35
        return $this->getInnerIterator()->current()['value'];
60
    }
61
62
    /**
63
     * As the manual says, "If two members compare as equal, their
64
     * order in the sorted array is undefined."  This means that the
65
     * sort used is not "stable" and may change the order of elements
66
     * that compare equal.
67
     *
68
     * Sometimes you really do need a stable sort. For example, if you
69
     * sort a list by one field, then sort it again by another field,
70
     * but don't want to lose the ordering from the previous field.
71
     * In that case it is better to use usort with a comparison
72
     * function that takes both fields into account, but if you can't
73
     * do that then use the function below. It is a merge sort, which
74
     * is guaranteed O(n*log(n)) complexity, which means it stays
75
     * reasonably fast even when you use larger lists (unlike
76
     * bubblesort and insertion sort, which are O(n^2)).
77
     *
78
     * http://www.php.net/manual/en/function.usort.php#38827
79
     *
80
     * @param array $array
81
     * @param \Closure $cmp_function
82
     */
83 37
    protected function mergeSort(array &$array, \Closure $cmp_function)
84
    {
85
        // Arrays of size < 2 require no action.
86 37
        if (count($array) < 2) {
87 37
            return;
88
        }
89
90
        // Split the array in half
91 37
        $halfway = count($array) / 2;
92 37
        $array1 = array_slice($array, 0, $halfway);
93 37
        $array2 = array_slice($array, $halfway);
94
95
        // Recurse to sort the two halves
96 37
        $this->mergesort($array1, $cmp_function);
97 37
        $this->mergesort($array2, $cmp_function);
98
99
        // If all of $array1 is <= all of $array2, just append them.
100 37
        if (call_user_func($cmp_function, end($array1), $array2[0]) < 1) {
101 33
            $array = array_merge($array1, $array2);
102 33
            return;
103
        }
104
105
        // Merge the two sorted arrays into a single sorted array
106 22
        $array = [];
107 22
        $ptr1 = $ptr2 = 0;
108 22
        while ($ptr1 < count($array1) && $ptr2 < count($array2)) {
109 22
            if (call_user_func($cmp_function, $array1[$ptr1], $array2[$ptr2]) < 1) {
110 11
                $array[] = $array1[$ptr1++];
111
            } else {
112 22
                $array[] = $array2[$ptr2++];
113
            }
114
        }
115
116
        // Merge the remainder
117 22
        while ($ptr1 < count($array1)) {
118 18
            $array[] = $array1[$ptr1++];
119
        }
120 22
        while ($ptr2 < count($array2)) {
121 10
            $array[] = $array2[$ptr2++];
122
        }
123 22
        return;
124
    }
125
}
126