This repository has been archived by the owner on Oct 18, 2023. It is now read-only.
/
LambdaUtils.php
100 lines (90 loc) · 2.64 KB
/
LambdaUtils.php
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php
namespace PerrysLambda;
use PerrysLambda\Exception\InvalidException;
class LambdaUtils
{
/**
* Converts strings, empty strings and NULL into a callable
* @param string|callable|null $mixed
* @return callable
* @throws \PerrysLambda\Exception\InvalidException
*/
public static function toSelectCallable($mixed=null)
{
// callable
if(is_callable($mixed))
{
return $mixed;
}
// nothing, return full row
elseif(is_null($mixed) || $mixed==="")
{
return function($v) { return $v; };
}
// row field from string
elseif(is_int($mixed) || is_float($mixed) || is_string($mixed))
{
return function($v) use($mixed)
{
if(is_object($v))
{
if(method_exists($v, $mixed))
{
return $v->$mixed();
}
return $v->$mixed;
}
else
{
return $v[$mixed];
}
};
}
throw new InvalidException("Could not convert expression of type ".gettype($mixed)." into a lambda callable");
}
/**
* Convert strings, numbers, booleans and arrays into a callable
* @param type $mixed
* @return type
* @throws InvalidException
*/
public static function toConditionCallable($mixed=null)
{
// callable
if(is_callable($mixed))
{
return $mixed;
}
// is bool
elseif(is_bool($mixed) || is_string($mixed) || is_numeric($mixed))
{
return function($v) use($mixed) { return $v===$mixed; };
}
// conditions from array
elseif(is_array($mixed) && count($mixed)>0)
{
return function($v) use($mixed)
{
foreach($mixed as $field => $expression)
{
if(is_callable($expression))
{
if($expression($v[$field])!==true)
{
return false;
}
}
else
{
if($v[$field]!==$expression)
{
return false;
}
}
}
return true;
};
}
throw new InvalidException("Could not convert expression of type ".gettype($mixed)." into a lambda callable");
}
}