4
4
5
5
use App \ApiJson \Parse \Parse ;
6
6
use App \Constants \ResponseCode ;
7
+ use App \Event \ApiJson \RequestHandleAfter ;
8
+ use App \Event \ApiJson \RequestHandleBefore ;
7
9
use Hyperf \HttpServer \Contract \RequestInterface ;
10
+ use Hyperf \Utils \ApplicationContext ;
11
+ use Psr \EventDispatcher \EventDispatcherInterface ;
8
12
9
13
class ApiJson
10
14
{
@@ -14,16 +18,28 @@ public function __construct(protected RequestInterface $request, protected strin
14
18
15
19
public function Query (): array
16
20
{
17
- if (!is_array (json_decode ($ this ->request ->getBody ()->getContents (), true ))) {
18
- return [
19
- 'code ' => ResponseCode::CODE_UNSUPPORTED_ENCODING ,
20
- 'msg ' => ResponseCode::getMessage (ResponseCode::CODE_UNSUPPORTED_ENCODING )
21
- ];
21
+ $ content = $ this ->request ->getBody ()->getContents ();
22
+ $ beforeEvent = new RequestHandleBefore ($ content , $ this ->method );
23
+ ApplicationContext::getContainer ()->get (EventDispatcherInterface::class)->dispatch ($ beforeEvent );
24
+
25
+ if (empty ($ beforeEvent ->response )) { //提供更多可能性, 如接入缓存功能
26
+ if (!is_array (json_decode ($ beforeEvent ->content , true ))) {
27
+ return [
28
+ 'code ' => ResponseCode::CODE_UNSUPPORTED_ENCODING ,
29
+ 'msg ' => ResponseCode::getMessage (ResponseCode::CODE_UNSUPPORTED_ENCODING )
30
+ ];
31
+ }
32
+ $ parse = new Parse (json_decode ($ beforeEvent ->content , true ), $ this ->method , $ this ->request ->input ('tag ' , '' ));
33
+ $ response = $ parse ->handle ();
34
+ } else {
35
+ $ response = $ beforeEvent ->response ;
22
36
}
23
- $ parse = new Parse (json_decode ($ this ->request ->getBody ()->getContents (), true ), $ this ->method , $ this ->request ->input ('tag ' , '' ));
37
+
38
+ ApplicationContext::getContainer ()->get (EventDispatcherInterface::class)->dispatch (new RequestHandleAfter ($ beforeEvent ->content , $ response ));
39
+
24
40
return array_merge ([
25
41
'code ' => ResponseCode::CODE_SUCCESS ,
26
42
'msg ' => ResponseCode::getMessage (ResponseCode::CODE_SUCCESS )
27
- ], $ parse -> handle () );
43
+ ], $ response );
28
44
}
29
45
}
0 commit comments