-
Notifications
You must be signed in to change notification settings - Fork 8
/
_.php
405 lines (368 loc) · 9.46 KB
/
_.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
<?php
namespace Dash;
/**
* Placeholder parameter for partial(), curry(), etc.
* @see partial(), curry()
*/
const _ = "\0\0";
/**
* Used to manage and access operations.
*
* All operations can be accessed as standalone static methods (eg. `_::map()`)
* or as chained methods (eg. `_::chain()->map()`).
*
* @example As standalone operations
_::map([1, 2, 3], function ($n) { return $n * 2; });
// === [2, 4, 6]
*
* @example As chained operations
_::chain([1, 2, 3])
->filter(function ($n) { return $n < 3; })
->map(function ($n) { return $n * 2; })
->value();
// === [2, 4]
*/
class _
{
/**
* Creates a global function alias for `_::chain()`.
*
* Note: This method should only be called once per `$alias`.
*
* @param string $alias Name of the global function to create
* @return void
* @throws RuntimeException if a global function with the same name already exists
*
* @example Aliases `_::chain()` to `dash()`
_::addGlobalAlias('dash');
dash([1, 2, 3])
->filter(function ($n) { return $n < 3; })
->map(function ($n) { return $n * 2; })
->value();
// === [2, 4]
*/
public static function addGlobalAlias($alias = '__')
{
if (function_exists($alias)) {
throw new \RuntimeException("A global function $alias() already exists");
}
if (!function_exists($alias)) {
eval("function $alias() { return call_user_func_array('Dash\_::chain', func_get_args()); }");
}
}
/**
* Creates a new chain.
*
* @param mixed $input (optional) Initial input value of the chain
* @return Dash\_ A new chain
*
* @example
_::chain([1, 2, 3])
->filter(function ($n) { return $n < 3; })
->map(function ($n) { return $n * 2; })
->value();
// === [2, 4]
*/
public static function chain($input = null)
{
return new self($input);
}
/**
* Sets a custom operation.
*
* A custom operation with the same name as a built-in operation
* will override the built-in operation.
*
* @param string $name Operation name
* @param callable $callable Operation function
* @param boolean $makeCurryable (optional) If true, a curried variant of the operation will also be added,
* with arguments rotated by 1 so that the first argument is now last,
* the second argument is now first, the third is now second, and so on
* @return void
* @throws Exception when attempting to create a custom method with the same name as a built-in Dash operation
*
* @example Custom operation for numbers
_::setCustom('triple', function ($n) { return $n * 3; });
_::triple(4);
// === 12
*
* @example Custom operation for iterables
_::setCustom('addEach', function ($iterable, $add) {
return _::map($iterable, function ($n) use ($add) { return $n + $add; });
});
_::chain([1, 2, 3])->addEach(3)->value();
// === [4, 5, 6]
*
* @example With automatic currying
_::setCustom('addEach', function ($iterable, $add) {
return _::map($iterable, function ($n) use ($add) { return $n + $add; });
});
$add3 = _::_addEach(3);
$add3([1, 2, 3]);
// === [4, 5, 6]
*/
public static function setCustom($name, callable $callable, $makeCurryable = true)
{
if (is_callable("\\Dash\\$name")) {
throw new \Exception(
"Cannot create a custom method named '$name'; Dash\\$name() already exists and cannot be overridden"
);
}
self::$customFunctions[$name] = $callable;
if ($makeCurryable) {
$curried = function () use ($callable) {
return currify($callable, func_get_args());
};
self::$customFunctions["_$name"] = $curried;
}
}
/**
* Removes a custom operation.
*
* @param string $name Name of the operation that was added via `setCustom()`
* @return void
*
* @example
_::setCustom('triple', function ($n) { return $n * 3; });
_::triple(4); // === 12
_::unsetCustom('triple');
_::triple(4); // Throws an exception
*/
public static function unsetCustom($name)
{
unset(self::$customFunctions[$name], self::$customFunctions["_$name"]);
}
/**
* Executes a standalone operation.
*
* @param string $method Method name
* @param array $args Method arguments
* @return mixed Return value of the method
* @throws BadMethodCallException if an invalid operation is called
*
* @example
_::map([1, 2, 3], function($n) { return $n * 2; });
// === [2, 4, 6]
*/
public static function __callStatic($method, $args)
{
return call_user_func_array(self::toCallable($method), $args);
}
/**
* Sets the input value of a chain.
*
* Can be called multiple times on the same chain.
*
* @param mixed $input
* @return _ The chain
*
* @example With an array
_::chain()->with([1, 2, 3])->value();
// === [1, 2, 3]
*
* @example With an stdClass
_::chain()->with((object) ['a' => 1, 'b' => 2, 'c' => 3])->value();
// === (object) ['a' => 1, 'b' => 2, 'c' => 3]
*
* @example With a number
_::chain()->with(3.14)->value();
// === 3.14
*/
public function with($input = null)
{
$this->input = $input;
$this->output = null;
return $this;
}
/**
* Executes all chained operations with the latest input.
*
* The result is cached, and multiple calls to value() will returned the cached value
* until the input value is changed or more operations are added to the chain.
*
* @return mixed The result of all chained operations on the input
*
* @example
$chain = _::chain([1, 2, 3])->map(function ($n) { return $n * 2; });
// map() is not called yet
$chain->value();
// Only now is map() called
// === [2, 4, 6]
*/
public function value()
{
if (!isset($this->output)) {
$this->output = $this->getOutput($this->input);
}
return $this->output;
}
/**
* Calls value() and returns the result as an array using toArray().
*
* @see toArray()
*
* @return array
*/
public function arrayValue()
{
return toArray($this->value());
}
/**
* Calls value() and returns the result as an object using toObject().
*
* @see toObject()
*
* @return stdClass
*/
public function objectValue()
{
return toObject($this->value());
}
/**
* Alias for value(). Useful for chains whose output is not needed.
*
* @see value()
* @return mixed
*
* @example
_::chain([1, 2, 3])
->each(function ($n) { echo $n; })
->run();
// Prints: 123
*/
public function run()
{
return $this->value();
}
/**
* Returns a new, independent copy of this chain.
*
* Future changes to this copy will not affect this original chain.
* This method is the same as cloning the chain.
*
* @return _
*
* @example
$original = _::chain()->map(function ($n) { return $n * 2; });
$original->with([1, 2, 3]);
$original->value();
// === [2, 4, 6]
$copy = $original->copy();
$copy->map(function ($n) { return $n + 1; });
$copy->with([4, 5, 6]);
$copy->value();
// === [9, 11, 13]
$original->with([1, 2, 3]);
$original->value();
// === [2, 4, 6]
*/
public function copy()
{
return clone $this;
}
/**
* Executes a chained operation on this chain.
*
* @param string $method Method name
* @param array $args Method args
* @return _ The chain
*
* @example
_::chain([1, 2, 3])
->filter(function($n) { return $n < 3; })
->map(function($n) { return $n * 2; })
->value();
// === [2, 4]
*/
public function __call($method, $args)
{
$this->operations[] = $this->toOperation($method, $args);
$this->output = null;
return $this;
}
/*
Private
------------------------------------------------------------
*/
/**
* Custom operation functions.
*
* @var array of operation name => callable
*/
private static $customFunctions = [];
/**
* The function operations to execute on this chain.
*
* @var array of callable
*/
private $operations = [];
/**
* The current input value of this chain.
*
* @var mixed
*/
private $input = null;
/**
* The cached output value (if any) of this chain.
*
* @var mixed
*/
private $output = null;
/**
* Returns a callable function for the specified operation.
*
* @param string $method Operation name (built-in or custom)
* @return callable Callable function for `$method`
* @throws BadMethodCallException if `$method` is not callable
*/
private static function toCallable($method)
{
if (is_callable("\\Dash\\$method")) {
return "\\Dash\\$method";
}
if (isset(self::$customFunctions[$method])) {
return self::$customFunctions[$method];
}
throw new \BadMethodCallException("No operation named '$method' found");
}
/**
* Constructs a new chain.
*
* @param mixed $input (optional) Input value of the chain
* @return void
*/
private function __construct($input = null)
{
$this->with($input);
}
/**
* Creates a new callable function that will invoke `$method` with `$args`.
*
* @param string $method Method name
* @param array $args Method arguments
* @return callable Callable function that will invoke `$method` with `$args` when called
*/
private function toOperation($method, $args)
{
$callable = self::toCallable($method);
$operation = function ($input) use ($callable, $args) {
array_unshift($args, $input);
return call_user_func_array($callable, $args);
};
return $operation;
}
/**
* Gets the result of all chained operations using `$input` as the initial input value.
*
* @param mixed $input
* @return array|scalar Result of all operations on `$input`
*/
private function getOutput($input)
{
$output = $input;
foreach ($this->operations as $operation) {
$output = call_user_func($operation, $output);
}
return $output;
}
}