-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHasResolver.php
99 lines (84 loc) · 2.43 KB
/
HasResolver.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
<?php
namespace Sikessem\Capsule;
use Sikessem\Capsule\Exception\NotFound;
use Sikessem\Capsule\Support\Singleton;
trait HasResolver
{
/**
* @var array<string,array<object|string>|string|object|callable(mixed ...$args): mixed>
*/
protected array $actions = [];
/**
* @var array<string,array<object|string>|string|object|callable(mixed ...$args): mixed>
*/
protected static array $ACTIONS = [];
/**
* @param array<object|string>|string|object|callable(mixed ...$args): mixed $action
*/
public function on(string $name, $action): static
{
$this->actions[$name] = $action;
return $this;
}
/**
* @param array<object|string>|string|object|callable(mixed ...$args): mixed $action
*/
public static function onStatic(string $name, $action): void
{
self::$ACTIONS[$name] = $action;
}
/**
* Allows you to call actions
*
* @param array<mixed> $args
*
* @throws NotFound When action is not defined
*/
public function resolve(string $name, array $args = []): mixed
{
foreach ($this->actions as $_name => $action) {
if ($_name != $name) {
continue;
}
if (! is_callable($action)) {
continue;
}
return Singleton::getContainer()->invoke($action, ...$args);
}
throw NotFound::with('Could not find action %s.', [$name]);
}
/**
* Allows to call static actions
*
* @param array<mixed> $args
*
* @throws NotFound When action is not defined
*/
public static function resolveStatic(string $name, array $args = []): mixed
{
foreach (static::$ACTIONS as $_name => $action) {
if ($_name !== $name) {
continue;
}
if (! is_callable($action)) {
continue;
}
return Singleton::getContainer()->invoke($action, ...$args);
}
throw NotFound::with('Could not find static action %s.', [$name]);
}
/**
* @param array<mixed> $args
*/
public function __call(string $name, array $args = []): mixed
{
return $this->resolve($name, $args);
}
/**
* @param array<mixed> $args
*/
public static function __callStatic(string $name, array $args = []): mixed
{
return static::resolveStatic($name, $args);
}
}