1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @copyright Zicht Online <http://zicht.nl> |
4
|
|
|
*/ |
5
|
|
|
|
6
|
|
|
namespace Zicht\Itertools\lib\Traits; |
7
|
|
|
|
8
|
|
|
use Zicht\Itertools\conversions; |
9
|
|
|
use Zicht\Itertools\lib\SortedIterator; |
10
|
|
|
|
11
|
|
View Code Duplication |
trait SortedTrait |
|
|
|
|
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* Make an iterator that returns the values from this iterable |
15
|
|
|
* sorted by $strategy |
16
|
|
|
* |
17
|
|
|
* When determining the order of two entries the $strategy is called |
18
|
|
|
* twice, once for each value, and the results are used to determine |
19
|
|
|
* the order. $strategy is called with two parameters: the value and |
20
|
|
|
* the key of the iterable as the first and second parameter, respectively. |
21
|
|
|
* |
22
|
|
|
* When $reverse is true the order of the results are reversed. |
23
|
|
|
* |
24
|
|
|
* The sorted() function is guaranteed to be stable. A sort is stable |
25
|
|
|
* if it guarantees not to change the relative order of elements that |
26
|
|
|
* compare equal. this is helpful for sorting in multiple passes (for |
27
|
|
|
* example, sort by department, then by salary grade). This also |
28
|
|
|
* holds up when $reverse is true. |
29
|
|
|
* |
30
|
|
|
* > $list = [['type'=>'B', 'title'=>'second'], ['type'=>'C', 'title'=>'third'], ['type'=>'A', 'title'=>'first']] |
31
|
|
|
* > iter\iterable($list)->sorted('type') |
32
|
|
|
* ['type'=>'A', 'title'=>'first'] ['type'=>'B', 'title'=>'second']] ['type'=>'C', 'title'=>'third'] |
33
|
|
|
* |
34
|
|
|
* @param null|string|\Closure $strategy |
35
|
|
|
* @param bool $reverse |
36
|
|
|
* @return SortedIterator |
37
|
|
|
*/ |
38
|
41 |
|
public function sorted($strategy = null, $reverse = false) |
39
|
|
|
{ |
40
|
41 |
|
if (!is_bool($reverse)) { |
41
|
1 |
|
throw new \InvalidArgumentException('Argument $reverse must be boolean'); |
42
|
|
|
} |
43
|
|
|
|
44
|
40 |
|
if ($this instanceof \Iterator) { |
45
|
39 |
|
return new SortedIterator( |
46
|
39 |
|
conversions\mixed_to_value_getter($strategy), |
|
|
|
|
47
|
37 |
|
$this, |
48
|
37 |
|
$reverse |
49
|
|
|
); |
50
|
|
|
} |
51
|
|
|
|
52
|
1 |
|
return null; |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
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.