Completed
Push — master ( bcd068...4006b8 )
by Georges
24s queued 13s
created

EventManager::setInstance()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 *
5
 * This file is part of Phpfastcache.
6
 *
7
 * @license MIT License (MIT)
8
 *
9
 * For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
10
 *
11
 * @author Georges.L (Geolim4)  <[email protected]>
12
 * @author Contributors  https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
13
 */
14
declare(strict_types=1);
15
16
namespace Phpfastcache;
17
18
use Phpfastcache\Event\EventManagerInterface;
19
use Phpfastcache\Exceptions\PhpfastcacheEventManagerException;
20
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
21
22
class EventManager implements EventManagerInterface
23
{
24
    public const ON_EVERY_EVENT = '__every';
25
26
    protected static self $instance;
27
28
    protected array $events = [
29
        self::ON_EVERY_EVENT => []
30
    ];
31
32
    /**
33
     * EventManager constructor.
34
     */
35
    final protected function __construct()
36
    {
37
        // The constructor should not be instantiated externally
38
    }
39
40
    /**
41
     * @return static
42
     */
43
    public static function getInstance(): static
44
    {
45
        return (self::$instance ?? self::$instance = new static());
46
    }
47
48
    /**
49
     * @param EventManagerInterface $eventManagerInstance
50
     * @return void
51
     */
52
    public static function setInstance(EventManagerInterface $eventManagerInstance): void
53
    {
54
        self::$instance = $eventManagerInstance;
55
    }
56
57
58
    /**
59
     * @param string $eventName
60
     * @param array $args
61
     */
62
    public function dispatch(string $eventName, ...$args): void
63
    {
64
        /**
65
         * Replace array_key_exists by isset
66
         * due to performance issue on huge
67
         * loop dispatching operations
68
         */
69
        if (isset($this->events[$eventName]) && $eventName !== self::ON_EVERY_EVENT) {
70
            $loopArgs = array_merge($args, [$eventName]);
71
            foreach ($this->events[$eventName] as $event) {
72
                $event(...$loopArgs);
73
            }
74
        }
75
        foreach ($this->events[self::ON_EVERY_EVENT] as $event) {
76
            $event($eventName, ...$args);
77
        }
78
    }
79
80
    /**
81
     * @param string $name
82
     * @param array $arguments
83
     * @throws PhpfastcacheInvalidArgumentException
84
     * @throws PhpfastcacheEventManagerException
85
     */
86
    public function __call(string $name, array $arguments): void
87
    {
88
        if (str_starts_with($name, 'on')) {
89
            $name = \substr($name, 2);
90
            if (\is_callable($arguments[0])) {
91
                if (isset($arguments[1]) && \is_string($arguments[0])) {
92
                    $this->events[$name][$arguments[1]] = $arguments[0];
93
                } else {
94
                    $this->events[$name][] = $arguments[0];
95
                }
96
            } else {
97
                throw new PhpfastcacheInvalidArgumentException(\sprintf('Expected Callable, got "%s"', \gettype($arguments[0])));
98
            }
99
        } else {
100
            throw new PhpfastcacheEventManagerException('An event must start with "on" such as "onCacheGetItem"');
101
        }
102
    }
103
104
    /**
105
     * @param callable $callback
106
     * @param string $callbackName
107
     */
108
    public function onEveryEvents(callable $callback, string $callbackName): void
109
    {
110
        $this->events[self::ON_EVERY_EVENT][$callbackName] = $callback;
111
    }
112
113
114
    /**
115
     * @throws PhpfastcacheEventManagerException
116
     */
117
    public function on(array $events, callable $callback): void
118
    {
119
        foreach ($events as $event) {
120
            if (!\preg_match('#^([a-zA-Z])*$#', $event)) {
121
                throw new PhpfastcacheEventManagerException(\sprintf('Invalid event name "%s"', $event));
122
            }
123
124
            $this->{'on' . \ucfirst($event)}($callback);
125
        }
126
    }
127
128
    /**
129
     * @param string $eventName
130
     * @param string $callbackName
131
     * @return bool
132
     */
133
    public function unbindEventCallback(string $eventName, string $callbackName): bool
134
    {
135
        $return = isset($this->events[$eventName][$callbackName]);
136
        unset($this->events[$eventName][$callbackName]);
137
138
        return $return;
139
    }
140
141
    /**
142
     * @return bool
143
     */
144
    public function unbindAllEventCallbacks(): bool
145
    {
146
        $this->events =  [
147
            self::ON_EVERY_EVENT => []
148
        ];
149
150
        return true;
151
    }
152
}
153