-
-
Notifications
You must be signed in to change notification settings - Fork 207
Expand file tree
/
Copy pathCurry.php
More file actions
53 lines (47 loc) · 1.62 KB
/
Copy pathCurry.php
File metadata and controls
53 lines (47 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
/**
* @package Functional-php
* @author Lars Strojny <lstrojny@php.net>
* @copyright 2011-2021 Lars Strojny
* @license https://opensource.org/licenses/MIT MIT
* @link https://github.com/lstrojny/functional-php
*/
namespace Functional;
use ReflectionMethod;
use ReflectionFunction;
use Closure;
/**
* Return a curried version of the given function. You can decide if you also
* want to curry optional parameters or not.
*
* @template V
* @template R
*
* @param callable(V...):R $function the function to curry
* @param bool $required curry optional parameters?
*
* @return callable(V...):R a curried version of the given function
*
* @no-named-arguments
*/
function curry(callable $function, $required = true)
{
if (\method_exists('Closure', 'fromCallable')) {
// Closure::fromCallable was introduced in PHP 7.1
$reflection = new ReflectionFunction(Closure::fromCallable($function));
} else {
if (\is_string($function) && \strpos($function, '::', 1) !== false) {
$reflection = new ReflectionMethod($function);
} elseif (\is_array($function) && \count($function) === 2) {
$reflection = new ReflectionMethod($function[0], $function[1]);
} elseif (\is_object($function) && \method_exists($function, '__invoke')) {
$reflection = new ReflectionMethod($function, '__invoke');
} else {
$reflection = new ReflectionFunction($function);
}
}
$count = $required ?
$reflection->getNumberOfRequiredParameters() :
$reflection->getNumberOfParameters();
return curry_n($count, $function);
}