-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathCallableFirstParameterExtractor.php
80 lines (62 loc) · 2.04 KB
/
CallableFirstParameterExtractor.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
<?php
declare(strict_types=1);
namespace CodelyTv\Shared\Infrastructure\Bus;
use CodelyTv\Shared\Domain\Bus\Event\DomainEventSubscriber;
use LogicException;
use ReflectionClass;
use ReflectionMethod;
use ReflectionNamedType;
use function Lambdish\Phunctional\map;
use function Lambdish\Phunctional\reduce;
use function Lambdish\Phunctional\reindex;
final class CallableFirstParameterExtractor
{
public static function forCallables(iterable $callables): array
{
return map(self::unflatten(), reindex(self::classExtractor(new self()), $callables));
}
public static function forPipedCallables(iterable $callables): array
{
return reduce(self::pipedCallablesReducer(), $callables, []);
}
private static function classExtractor(self $parameterExtractor): callable
{
return static fn (object $handler): ?string => $parameterExtractor->extract($handler);
}
private static function pipedCallablesReducer(): callable
{
return static function (array $subscribers, DomainEventSubscriber $subscriber): array {
$subscribedEvents = $subscriber::subscribedTo();
foreach ($subscribedEvents as $subscribedEvent) {
$subscribers[$subscribedEvent][] = $subscriber;
}
return $subscribers;
};
}
private static function unflatten(): callable
{
return static fn (mixed $value): array => [$value];
}
public function extract(object $class): ?string
{
$reflector = new ReflectionClass($class);
$method = $reflector->getMethod('__invoke');
if ($this->hasOnlyOneParameter($method)) {
return $this->firstParameterClassFrom($method);
}
return null;
}
private function firstParameterClassFrom(ReflectionMethod $method): string
{
/** @var ReflectionNamedType|null $fistParameterType */
$fistParameterType = $method->getParameters()[0]->getType();
if ($fistParameterType === null) {
throw new LogicException('Missing type hint for the first parameter of __invoke');
}
return $fistParameterType->getName();
}
private function hasOnlyOneParameter(ReflectionMethod $method): bool
{
return $method->getNumberOfParameters() === 1;
}
}