Completed
Push — master ( 26c0e4...9b2530 )
by Julián
01:22
created

AbstractEventHandler::isEventSupported()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
cc 3
nc 3
nop 1
1
<?php
2
3
/*
4
 * event (https://github.com/phpgears/event).
5
 * Event handling.
6
 *
7
 * @license MIT
8
 * @link https://github.com/phpgears/event
9
 * @author Julián Gutiérrez <[email protected]>
10
 */
11
12
declare(strict_types=1);
13
14
namespace Gears\Event;
15
16
use Gears\Event\Exception\InvalidEventException;
17
18
abstract class AbstractEventHandler implements EventHandler
19
{
20
    /**
21
     * {@inheritdoc}
22
     *
23
     * @throws InvalidEventException
24
     */
25
    final public function handle(Event $event): void
26
    {
27
        if (!$this->isEventSupported($event)) {
28
            throw new InvalidEventException(\sprintf(
29
                'Event must be a %s, %s given',
30
                \implode('or ', $this->getSupportedEventTypes()),
31
                \get_class($event)
32
            ));
33
        }
34
35
        $this->handleEvent($event);
36
    }
37
38
    /**
39
     * Is event supported.
40
     *
41
     * @param Event $event
42
     *
43
     * @return bool
44
     */
45
    private function isEventSupported(Event $event): bool
46
    {
47
        $supported = false;
48
49
        foreach ($this->getSupportedEventTypes() as $supportedEventType) {
50
            if (\is_a($event, $supportedEventType)) {
51
                $supported = true;
52
53
                break;
54
            }
55
        }
56
57
        return $supported;
58
    }
59
60
    /**
61
     * Get supported event type.
62
     *
63
     * @return string[]
64
     */
65
    abstract protected function getSupportedEventTypes(): array;
66
67
    /**
68
     * Handle event.
69
     *
70
     * @param Event $event
71
     */
72
    abstract protected function handleEvent(Event $event): void;
73
}
74