Completed
Pull Request — master (#2)
by Siwapun
13:33
created

curryN()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.6
c 0
b 0
f 0
cc 3
nc 1
nop 2
1
<?php
2
namespace Aerophant\Ramda;
3
4
/**
5
 * @param int $a
6
 * @param int $b
7
 * @return int
8
 */
9
function add()
10
{
11
  $add = function (int $a, int $b) {
12
    return $a + $b;
13
  };
14
  $arguments = func_get_args();
15
  $curried = curryN($add, 2);
16
  return call_user_func_array($curried, $arguments);
17
}
18
19
/**
20
 * @param mixed $data
21
 * @return \Closure
22
 */
23
function always()
24
{
25
  $always = function ($data) {
26
    return function () use ($data) {
27
      return $data;
28
    };
29
  };
30
  $arguments = func_get_args();
31
  $curried = curryN($always, 1);
32
  return call_user_func_array($curried, $arguments);
33
}
34
35
/**
36
 * @return callable
37
 * @throws \Exception
38
 */
39
function compose()
40
{
41
  $arguments = array_reverse(func_get_args());
42
  return call_user_func_array('Aerophant\Ramda\pipe', $arguments);
43
}
44
45
function curryN(callable $fn, int $numberOfArguments)
46
{
47
  return function () use ($fn, $numberOfArguments) {
48
    $arguments = func_get_args();
49
    $length = count($arguments);
50
    if ($length > $numberOfArguments) {
51
      throw new \InvalidArgumentException(
52
        "Number of passed($length) parameters is greater than expected($numberOfArguments)"
53
      );
54
    }
55
    // NO CURRY
56
    if ($length == $numberOfArguments) {
57
      return call_user_func_array($fn, $arguments);
58
    }
59
    // AUTO CURRY
60
    $curriedFn = function () use ($fn, $arguments) {
61
      $curriedArguments = func_get_args();
62
      return call_user_func_array($fn, array_merge($arguments, $curriedArguments));
63
    };
64
    return curryN($curriedFn, $numberOfArguments - $length);
65
  };
66
}
67
68
//TODO change to construct
69
function factory($class)
70
{
71
  return function () use ($class) {
72
    return new $class();
73
  };
74
}
75
76
/**
77
 * @return callable
78
 * @throws \Exception
79
 */
80
function pipe()
81
{
82
  $arguments = func_get_args();
83
  $length = count($arguments);
84
  if ($length === 0) {
85
    throw new \Exception("pipe requires at least one argument");
86
  }
87
  return function () use ($arguments) {
88
    $internalArguments = func_get_args();
89
    $initialValue = call_user_func_array($arguments[0], $internalArguments);
90
    $accumulator = function ($acc, $it) {
91
      return call_user_func_array($it, [$acc]);
92
    };
93
    return array_reduce(drop(0, $arguments), $accumulator, $initialValue);
94
  };
95
}
96