Skip to content

Commit 047dd26

Browse files
author
Andrii Savluk
committed
v1.3.0
1 parent e8980ab commit 047dd26

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/ContextsReducer.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<?php
2+
3+
namespace Savks\PhpContexts;
4+
5+
use Closure;
6+
7+
class ContextsReducer
8+
{
9+
protected array $contexts;
10+
11+
public function __construct(Context ...$context)
12+
{
13+
$this->contexts = $context;
14+
}
15+
16+
public function prepend(Context $context): static
17+
{
18+
array_unshift($this->contexts, $context);
19+
20+
return $this;
21+
}
22+
23+
public function append(Context $context): static
24+
{
25+
$this->contexts[] = $context;
26+
27+
return $this;
28+
}
29+
30+
public function wrap(Closure $callback): mixed
31+
{
32+
$resultCallback = array_reduce(
33+
array_reverse($this->contexts),
34+
function (Closure $callback, Context $context) {
35+
return fn () => $context->wrap($callback);
36+
},
37+
$callback
38+
);
39+
40+
return $resultCallback();
41+
}
42+
}

0 commit comments

Comments
 (0)