1 | <?php |
||
2 | declare(strict_types=1); |
||
3 | |||
4 | namespace Ctefan\Redux; |
||
5 | |||
6 | use Ctefan\Redux\Action\ActionInterface; |
||
7 | use Ctefan\Redux\Exception\IsSettingUpMiddlewareException; |
||
8 | use Ctefan\Redux\Store\EnhanceableStoreInterface; |
||
9 | use Ctefan\Redux\Store\Store; |
||
10 | |||
11 | class Redux |
||
12 | { |
||
13 | 11 | static public function createStore(callable $reducer, array $initialState = [], callable $enhancer = null): EnhanceableStoreInterface |
|
14 | { |
||
15 | 11 | if (null !== $enhancer) { |
|
16 | $createStore = [self::class, 'create']; |
||
17 | return $enhancer($createStore)($reducer, $initialState); |
||
18 | } |
||
19 | |||
20 | 11 | return new Store($reducer, $initialState); |
|
21 | } |
||
22 | |||
23 | 4 | static public function applyMiddleware(callable ...$middlewares): callable |
|
24 | { |
||
25 | return function(callable $createStore) use ($middlewares): callable { |
||
26 | return function(callable $reducer, array $initialState = [], callable $enhancer = null) use ($middlewares, $createStore): EnhanceableStoreInterface { |
||
27 | 4 | $store = $createStore($reducer, $initialState, $enhancer); |
|
28 | |||
29 | 4 | $getStateFunction = [$store, 'getState']; |
|
30 | $dispatchFunction = function(ActionInterface $action) { |
||
0 ignored issues
–
show
|
|||
31 | 1 | throw new IsSettingUpMiddlewareException( |
|
32 | 'Dispatching while constructing your middleware is not allowed. ' . |
||
33 | 1 | 'Other middleware would not be applied to this dispatch.' |
|
34 | ); |
||
35 | 4 | }; |
|
36 | |||
37 | $chain = array_map(function($middleware) use ($getStateFunction, $dispatchFunction): callable { |
||
38 | 4 | return $middleware($getStateFunction, $dispatchFunction); |
|
39 | 4 | }, $middlewares); |
|
40 | |||
41 | 3 | $dispatchFunction = self::compose(...$chain)($store->getDispatcher()); |
|
42 | |||
43 | 3 | $store->setDispatcher($dispatchFunction); |
|
44 | |||
45 | 3 | return $store; |
|
46 | 4 | }; |
|
47 | 4 | }; |
|
48 | } |
||
49 | |||
50 | 6 | static public function compose(callable ...$callables): callable |
|
51 | { |
||
52 | 6 | if (0 === count($callables)) { |
|
53 | return function($argument) { |
||
54 | return $argument; |
||
55 | 1 | }; |
|
56 | } |
||
57 | |||
58 | 5 | if (1 === count($callables)) { |
|
59 | 3 | return $callables[0]; |
|
60 | } |
||
61 | |||
62 | return array_reduce($callables, function(?callable $previous, callable $next): callable { |
||
63 | 2 | if (null === $previous) { |
|
64 | 2 | return $next; |
|
65 | } |
||
66 | return function(...$arguments) use ($previous, $next) { |
||
67 | 1 | return $previous($next(...$arguments)); |
|
68 | 2 | }; |
|
69 | 2 | }); |
|
70 | } |
||
71 | } |
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.