Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
81.82% covered (warning)
81.82%
9 / 11
66.67% covered (warning)
66.67%
2 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
SortArrayByKeys
81.82% covered (warning)
81.82%
9 / 11
66.67% covered (warning)
66.67%
2 / 3
9.49
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 __invoke
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 compare
75.00% covered (warning)
75.00%
6 / 8
0.00% covered (danger)
0.00%
0 / 1
7.77
1<?php
2
3namespace Flow\Data\Utils;
4
5/**
6 * Performs the equivalent of an SQL ORDER BY c1 ASC, c2 ASC...
7 * Always sorts in ascending order.  array_reverse to get all descending.
8 * For varied asc/desc needs implementation changes.
9 *
10 * usage: usort( $array, new SortArrayByKeys( [ 'c1', 'c2' ] ) );
11 */
12class SortArrayByKeys {
13    /** @var array */
14    protected $keys;
15    /** @var bool */
16    protected $strict;
17
18    public function __construct( array $keys, $strict = false ) {
19        $this->keys = $keys;
20        $this->strict = $strict;
21    }
22
23    public function __invoke( $a, $b ) {
24        return self::compare( $a, $b, $this->keys, $this->strict );
25    }
26
27    public static function compare( $a, $b, array $keys, $strict = false ) {
28        $key = array_shift( $keys );
29        if ( !isset( $a[$key] ) ) {
30            return isset( $b[$key] ) ? -1 : 0;
31        } elseif ( !isset( $b[$key] ) ) {
32            return 1;
33        } elseif ( $strict ? $a[$key] === $b[$key] : $a[$key] == $b[$key] ) {
34            return $keys ? self::compare( $a, $b, $keys, $strict ) : 0;
35        } else { // is there such a thing as strict gt/lt ?
36            return $a[$key] <=> $b[$key];
37        }
38    }
39}