chengkun
2025-09-15 0cc7f61de2b106c9664033fc27d6426d072ea019
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2025 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);
 
namespace think;
 
use ReflectionClass;
use ReflectionMethod;
use think\helper\Str;
 
/**
 * 事件管理类
 * @package think
 */
class Event
{
    /**
     * 监听者
     * @var array
     */
    protected $listener = [];
 
    /**
     * 观察者
     * @var array
     */
    protected $observer = [];
 
    /**
     * 事件别名
     * @var array
     */
    protected $bind = [
        'AppInit'     => event\AppInit::class,
        'HttpRun'     => event\HttpRun::class,
        'HttpEnd'     => event\HttpEnd::class,
        'RouteLoaded' => event\RouteLoaded::class,
        'LogWrite'    => event\LogWrite::class,
        'LogRecord'   => event\LogRecord::class,
    ];
 
    /**
     * 应用对象
     * @var App
     */
    protected $app;
 
    public function __construct(App $app)
    {
        $this->app = $app;
    }
 
    /**
     * 批量注册事件监听
     * @access public
     * @param array $events 事件定义
     * @return $this
     */
    public function listenEvents(array $events)
    {
        foreach ($events as $event => $listeners) {
            if (isset($this->bind[$event])) {
                $event = $this->bind[$event];
            }
 
            $this->listener[$event] = array_merge($this->listener[$event] ?? [], $listeners);
        }
 
        return $this;
    }
 
    /**
     * 注册事件监听
     * @access public
     * @param string $event    事件名称
     * @param mixed  $listener 监听操作(或者类名)
     * @param bool   $first    是否优先执行
     * @return $this
     */
    public function listen(string $event, $listener, bool $first = false)
    {
        if (isset($this->bind[$event])) {
            $event = $this->bind[$event];
        }
 
        if ($first && isset($this->listener[$event])) {
            array_unshift($this->listener[$event], $listener);
        } else {
            $this->listener[$event][] = $listener;
        }
 
        return $this;
    }
 
    /**
     * 是否存在事件监听
     * @access public
     * @param string $event 事件名称
     * @return bool
     */
    public function hasListener(string $event): bool
    {
        if (isset($this->bind[$event])) {
            $event = $this->bind[$event];
        }
 
        return isset($this->listener[$event]);
    }
 
    /**
     * 移除事件监听
     * @access public
     * @param string $event 事件名称
     * @return void
     */
    public function remove(string $event): void
    {
        if (isset($this->bind[$event])) {
            $event = $this->bind[$event];
        }
 
        unset($this->listener[$event]);
    }
 
    /**
     * 指定事件别名标识 便于调用
     * @access public
     * @param array $events 事件别名
     * @return $this
     */
    public function bind(array $events)
    {
        $this->bind = array_merge($this->bind, $events);
 
        return $this;
    }
 
    /**
     * 注册事件订阅者
     * @access public
     * @param mixed $subscriber 订阅者
     * @return $this
     */
    public function subscribe($subscriber)
    {
        $subscribers = is_object($subscriber) ? [$subscriber] : (array) $subscriber;
 
        foreach ($subscribers as $name => $subscriber) {
            if (is_string($subscriber)) {
                $subscriber = $this->app->make($subscriber);
            }
 
            if (method_exists($subscriber, 'subscribe')) {
                // 手动订阅
                $subscriber->subscribe($this);
            } elseif (!is_numeric($name)) {
                // 注册观察者
                $this->observer[$name] = $subscriber;
            } else {
                // 智能订阅
                $this->observe($subscriber);
            }
        }
 
        return $this;
    }
 
    /**
     * 自动注册事件监听
     * @access public
     * @param string|object $observer 观察者
     * @param null|string   $prefix   事件名前缀
     * @return $this
     */
    public function observe($observer, string $prefix = '')
    {
        if (is_string($observer)) {
            $observer = $this->app->make($observer);
        }
 
        $reflect = new ReflectionClass($observer);
        $methods = $reflect->getMethods(ReflectionMethod::IS_PUBLIC);
 
        if (empty($prefix) && $reflect->hasProperty('eventPrefix')) {
            $reflectProperty = $reflect->getProperty('eventPrefix');
            $reflectProperty->setAccessible(true);
            $prefix = $reflectProperty->getValue($observer);
        }
 
        foreach ($methods as $method) {
            $name = $method->getName();
            if (str_starts_with($name, 'on')) {
                $this->listen($prefix . substr($name, 2), [$observer, $name]);
            }
        }
 
        return $this;
    }
 
    /**
     * 触发事件
     * @access public
     * @param string|object $event  事件名称
     * @param mixed         $params 传入参数
     * @param bool          $once   只获取一个有效返回值
     * @return mixed
     */
    public function trigger($event, $params = null, bool $once = false)
    {
        if (is_object($event)) {
            $params = $event;
            $event  = $event::class;
        }
 
        if (isset($this->bind[$event])) {
            $event = $this->bind[$event];
        }
 
        $result    = [];
        $listeners = $this->listener[$event] ?? [];
 
        if (str_contains($event, '.')) {
            [$prefix, $name] = explode('.', $event, 2);
            if (isset($this->observer[$prefix])) {
                // 检查观察者事件响应方法
                $observer = $this->observer[$prefix];
                $method   = 'on' . Str::studly($name);
                if (method_exists($observer, $method)) {
                    return $this->dispatch([$observer, $method], $params);
                }
            }
 
            $name = substr($event, 0, strrpos($event, '.'));
            if (isset($this->listener[$name . '.*'])) {
                $listeners = array_merge($listeners, $this->listener[$name . '.*']);
            }
        }
 
        $listeners = array_unique($listeners, SORT_REGULAR);
 
        foreach ($listeners as $key => $listener) {
            $result[$key] = $this->dispatch($listener, $params);
 
            if (false === $result[$key] || (!is_null($result[$key]) && $once)) {
                break;
            }
        }
 
        return $once ? end($result) : $result;
    }
 
    /**
     * 触发事件(只获取一个有效返回值)
     * @param      $event
     * @param null $params
     * @return mixed
     */
    public function until($event, $params = null)
    {
        return $this->trigger($event, $params, true);
    }
 
    /**
     * 执行事件调度
     * @access protected
     * @param mixed $event  事件方法
     * @param mixed $params 参数
     * @return mixed
     */
    protected function dispatch($event, $params = null)
    {
        if (!is_string($event)) {
            $call = $event;
        } elseif (str_contains($event, '::')) {
            $call = $event;
        } else {
            $obj  = $this->app->make($event);
            $call = [$obj, 'handle'];
        }
 
        return $this->app->invoke($call, [$params]);
    }
}