-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathEventAttributePresenter.php
More file actions
75 lines (67 loc) · 2.36 KB
/
Copy pathEventAttributePresenter.php
File metadata and controls
75 lines (67 loc) · 2.36 KB
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
<?php
namespace Mbunge\PhpAttributes\Example\PhpLeagueEvent;
use League\Event\ListenerRegistry;
use Mbunge\PhpAttributes\Example\PhpLeagueEvent\Attribute\SubscribeTo;
use Mbunge\PhpAttributes\Presenter\AttributePresenterInterface;
use Mbunge\PhpAttributes\Resolver\ResolvedAttributeDto;
use ReflectionException;
use ReflectionMethod;
use function array_filter;
/**
* This presenters takes all matching SubscribeTo attribute instances
* and registers events by SubscribeTo::name and it's reflection
*
* Class EventAttributePresenter
* @copyright Marco Bunge <marco_bunge@web.de>
* @package Mbunge\PhpAttributes\Example\PhpLeagueEvent;
*/
class EventAttributePresenter implements AttributePresenterInterface
{
public function __construct(
private ListenerRegistry $eventListenerRegistry
)
{
}
/**
* Takes all matching attributes and register event listener
*
* @param array $attributes
* @return array
* @throws ReflectionException
*/
public function present(array $attributes): array
{
// restrict to SubscribeTo instances
$validAttributes = array_filter(
$attributes,
fn(ResolvedAttributeDto $dto) => $dto->getAttribute() instanceof SubscribeTo
&& $dto->getReflectedTarget() instanceof ReflectionMethod
);
// run matching attributes and register event listeners (subscriber)
return array_map(
fn(ResolvedAttributeDto $dto) => $this->registerListener($dto),
$validAttributes
);
}
/**
* Takes event name from attribute and convert reflection to callable listener
* @param ResolvedAttributeDto $dto
* @return ResolvedAttributeDto
* @throws ReflectionException
*/
private function registerListener(ResolvedAttributeDto $dto): ResolvedAttributeDto {
/** @var ReflectionMethod $reflection */
$reflection = $dto->getReflectedTarget();
/** @var SubscribeTo $attribute */
$attribute = $dto->getAttribute();
$this->eventListenerRegistry->subscribeTo(
$attribute->event,
[
// could be replaced by psr-11 container::get to resolve dependecies
$reflection->getDeclaringClass()->newInstanceWithoutConstructor(),
$reflection->getName()
]
);
return $dto;
}
}