Completed
Pull Request — master (#20)
by Siwapun
06:34 queued 04:49
created

pathOr()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
nc 1
nop 0
dl 0
loc 9
ccs 6
cts 6
cp 1
crap 2
rs 9.9666
c 0
b 0
f 0
1
<?php
2
namespace Aerophant\Ramda;
3
4
/**
5
 * @param array $paths
6
 * @param mixed $obj
7
 * @return mixed|\Closure
8
 */
9
function path()
10
{
11
  $path = function (array $paths, $obj) {
12 10
    return reduce(
13
      function ($acc, $item) {
14 10
        if ($acc === null) {
15
          return null;
16
        }
17 10
        if (is_array($acc)) {
18 8
          return array_key_exists($item, $acc) ? $acc[$item] : null;
19
        }
20 2
        throw new \InvalidArgumentException('path(array $paths, $obj) only support array object');
21 10
      },
22 10
      $obj,
23 10
      $paths
24
    );
25 10
  };
26 10
  $arguments = func_get_args();
27 10
  $curried = curryN($path, 2);
28 10
  return call_user_func_array($curried, $arguments);
29
}
30
31
/**
32
 * @param mixed $defaultValue
33
 * @param array $paths
34
 * @param mixed $obj
35
 * @return mixed|\Closure
36
 */
37
function pathOr()
38
{
39
  $pathOr = function ($defaultValue, array $paths, $obj) {
40 5
    $value = path($paths, $obj);
41 4
    return $value ? $value : $defaultValue;
42 5
  };
43 5
  $arguments = func_get_args();
44 5
  $curried = curryN($pathOr, 3);
45 5
  return call_user_func_array($curried, $arguments);
46
}
47