Completed
Branch master (56c2f5)
by
unknown
07:05
created

Util::arrayMapWithIndex()   C

Complexity

Conditions 8
Paths 7

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 6.1403
c 0
b 0
f 0
cc 8
eloc 14
nc 7
nop 2
1
<?php
2
3
namespace Blocktrail\SDK;
4
5
abstract class Util {
6
    public static function all(callable $fn, array $arr) {
7
        $allvalues = array_map($fn, $arr);
8
        return count(array_unique($allvalues)) === 1 && end($allvalues) === true;
9
    }
10
11
    public static function arrayMapWithIndex(callable $fn, $arr) {
12
        $result = [];
13
        $assoc = null;
14
        foreach ($arr as $idx => $value) {
15
            list($newidx, $newvalue) = $fn($idx, $value);
16
17
            if ($assoc === null) {
18
                $assoc = $newidx !== null;
19
            }
20
21
            if ($newidx === null && $assoc || $newidx !== null && !$assoc) {
22
                throw new \Exception("Mix of non assoc and assoc keys");
23
            }
24
25
            if ($assoc) {
26
                $result[$newidx] = $newvalue;
27
            } else {
28
                $result[] = $newvalue;
29
            }
30
        }
31
32
        return $result;
33
    }
34
}
35