Completed
Pull Request — 6.0 (#2115)
by nhzex
06:13
created

Event::remove()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
6
// +----------------------------------------------------------------------
7
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
8
// +----------------------------------------------------------------------
9
// | Author: liu21st <[email protected]>
10
// +----------------------------------------------------------------------
11
declare (strict_types = 1);
12
13
namespace think;
14
15
use ReflectionClass;
16
use ReflectionMethod;
17
18
/**
19
 * 事件管理类
20
 * @package think
0 ignored issues
show
Coding Style introduced by
Package name "think" is not valid; consider "Think" instead
Loading history...
21
 */
22
class Event
23
{
24
    /**
25
     * 监听者
26
     * @var array
27
     */
28
    protected $listener = [];
29
30
    /**
31
     * 事件别名
32
     * @var array
33
     */
34
    protected $bind = [
35
        'AppInit'     => event\AppInit::class,
36
        'HttpRun'     => event\HttpRun::class,
37
        'HttpEnd'     => event\HttpEnd::class,
38
        'RouteLoaded' => event\RouteLoaded::class,
39
        'LogWrite'    => event\LogWrite::class,
40
    ];
41
42
    /**
43
     * 是否需要事件响应
44
     * @var bool
45
     */
46
    protected $withEvent = true;
47
48
    /**
49
     * 应用对象
50
     * @var App
51
     */
52
    protected $app;
53
54 10
    public function __construct(App $app)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
55
    {
56 10
        $this->app = $app;
57 10
    }
58
59
    /**
60
     * 设置是否开启事件响应
61
     * @access protected
62
     * @param bool $event 是否需要事件响应
63
     * @return $this
64
     */
65 2
    public function withEvent(bool $event)
66
    {
67 2
        $this->withEvent = $event;
68 2
        return $this;
69
    }
70
71
    /**
72
     * 批量注册事件监听
73
     * @access public
74
     * @param array $events 事件定义
75
     * @return $this
76
     */
77 1
    public function listenEvents(array $events)
78
    {
79 1
        if (!$this->withEvent) {
80
            return $this;
81
        }
82
83 1
        foreach ($events as $event => $listeners) {
84 1
            if (isset($this->bind[$event])) {
85
                $event = $this->bind[$event];
86
            }
87
88 1
            $this->listener[$event] = array_merge($this->listener[$event] ?? [], $listeners);
89
        }
90
91 1
        return $this;
92
    }
93
94
    /**
95
     * 注册事件监听
96
     * @access public
97
     * @param string $event    事件名称
98
     * @param mixed  $listener 监听操作(或者类名)
99
     * @param bool   $first    是否优先执行
100
     * @return $this
101
     */
102 5
    public function listen(string $event, $listener, bool $first = false)
103
    {
104 5
        if (!$this->withEvent) {
105 1
            return $this;
106
        }
107
108 4
        if (isset($this->bind[$event])) {
109 2
            $event = $this->bind[$event];
110
        }
111
112 4
        if ($first && isset($this->listener[$event])) {
113
            array_unshift($this->listener[$event], $listener);
114
        } else {
115 4
            $this->listener[$event][] = $listener;
116
        }
117
118 4
        return $this;
119
    }
120
121
    /**
122
     * 是否存在事件监听
123
     * @access public
124
     * @param string $event 事件名称
125
     * @return bool
126
     */
127 3
    public function hasListener(string $event): bool
128
    {
129 3
        if (isset($this->bind[$event])) {
130 1
            $event = $this->bind[$event];
131
        }
132
133 3
        return isset($this->listener[$event]);
134
    }
135
136
    /**
137
     * 移除事件监听
138
     * @access public
139
     * @param string $event 事件名称
140
     * @return void
141
     */
142 1
    public function remove(string $event): void
143
    {
144 1
        if (isset($this->bind[$event])) {
145 1
            $event = $this->bind[$event];
146
        }
147
148 1
        unset($this->listener[$event]);
149 1
    }
150
151
    /**
152
     * 指定事件别名标识 便于调用
153
     * @access public
154
     * @param array $events 事件别名
155
     * @return $this
156
     */
157 1
    public function bind(array $events)
158
    {
159 1
        $this->bind = array_merge($this->bind, $events);
160
161 1
        return $this;
162
    }
163
164
    /**
165
     * 注册事件订阅者
166
     * @access public
167
     * @param mixed $subscriber 订阅者
168
     * @return $this
169
     */
170 1
    public function subscribe($subscriber)
171
    {
172 1
        if (!$this->withEvent) {
173
            return $this;
174
        }
175
176 1
        $subscribers = (array) $subscriber;
177
178 1
        foreach ($subscribers as $subscriber) {
0 ignored issues
show
introduced by
$subscriber is overwriting one of the parameters of this function.
Loading history...
179 1
            if (is_string($subscriber)) {
180 1
                $subscriber = $this->app->make($subscriber);
181
            }
182
183 1
            if (method_exists($subscriber, 'subscribe')) {
184
                // 手动订阅
185 1
                $subscriber->subscribe($this);
186
            } else {
187
                // 智能订阅
188
                $this->observe($subscriber);
189
            }
190
        }
191
192 1
        return $this;
193
    }
194
195
    /**
196
     * 自动注册事件观察者
197
     * @access public
198
     * @param string|object $observer 观察者
199
     * @param null|string   $prefix   事件名前缀
200
     * @return $this
201
     */
202 1
    public function observe($observer, string $prefix = '')
203
    {
204 1
        if (!$this->withEvent) {
205
            return $this;
206
        }
207
208 1
        if (is_string($observer)) {
209 1
            $observer = $this->app->make($observer);
210
        }
211
212 1
        $reflect = new ReflectionClass($observer);
213 1
        $methods = $reflect->getMethods(ReflectionMethod::IS_PUBLIC);
214
215 1
        if (empty($prefix) && $reflect->hasProperty('eventPrefix')) {
216
            $reflectProperty = $reflect->getProperty('eventPrefix');
217
            $reflectProperty->setAccessible(true);
218
            $prefix = $reflectProperty->getValue($observer);
219
        }
220
221 1
        foreach ($methods as $method) {
222 1
            $name = $method->getName();
223 1
            if (0 === strpos($name, 'on')) {
224 1
                $this->listen($prefix . substr($name, 2), [$observer, $name]);
225
            }
226
        }
227
228 1
        return $this;
229
    }
230
231
    /**
232
     * 触发事件
233
     * @access public
234
     * @param string|object $event  事件名称
235
     * @param mixed         $params 传入参数
236
     * @param bool          $once   只获取一个有效返回值
237
     * @return mixed
238
     */
239 8
    public function trigger($event, $params = null, bool $once = false)
240
    {
241 8
        if (!$this->withEvent) {
242
            return;
243
        }
244
245 8
        if (is_object($event)) {
246 2
            $params = $event;
247 2
            $event  = get_class($event);
248
        }
249
250 8
        if (isset($this->bind[$event])) {
251 1
            $event = $this->bind[$event];
252
        }
253
254 8
        $result    = [];
255 8
        $listeners = $this->listener[$event] ?? [];
256 8
        $listeners = array_unique($listeners, SORT_REGULAR);
257
258 8
        foreach ($listeners as $key => $listener) {
259 4
            $result[$key] = $this->dispatch($listener, $params);
260
261 4
            if (false === $result[$key] || (!is_null($result[$key]) && $once)) {
262 3
                break;
263
            }
264
        }
265
266 8
        return $once ? end($result) : $result;
267
    }
268
269
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $event should have a doc-comment as per coding-style.
Loading history...
270
     * 触发事件(只获取一个有效返回值)
271
     * @param      $event
0 ignored issues
show
Coding Style Documentation introduced by
Missing parameter name
Loading history...
272
     * @param null $params
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $params is correct as it would always require null to be passed?
Loading history...
Coding Style introduced by
Missing parameter comment
Loading history...
273
     * @return mixed
274
     */
275 1
    public function until($event, $params = null)
276
    {
277 1
        return $this->trigger($event, $params, true);
278
    }
279
280
    /**
281
     * 执行事件调度
282
     * @access protected
283
     * @param mixed $event  事件方法
284
     * @param mixed $params 参数
285
     * @return mixed
286
     */
287 4
    protected function dispatch($event, $params = null)
288
    {
289 4
        if (!is_string($event)) {
290 3
            $call = $event;
291 1
        } elseif (strpos($event, '::')) {
292
            $call = $event;
293
        } else {
294 1
            $obj  = $this->app->make($event);
295 1
            $call = [$obj, 'handle'];
296
        }
297
298 4
        return $this->app->invoke($call, [$params]);
299
    }
300
301
}
302