Completed
Pull Request — master (#4)
by Siwapun
21:56 queued 06:35
created

construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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