11<?php
22
3- namespace Plugins \ FresnsEngine ;
3+ namespace ZhenMu \ Support \ Traits ;
44
55trait Clientable
66{
@@ -11,12 +11,15 @@ trait Clientable
1111
1212 protected array $ result = [];
1313
14- public static function make ()
14+ public static function make (): static | \ GuzzleHttp \ Promise \ Utils | \ GuzzleHttp \ Client
1515 {
1616 return new static ();
1717 }
1818
19- abstract public function getHttpClient ();
19+ public function getHttpClient ()
20+ {
21+ return new \GuzzleHttp \Client ($ this ->getOptions ());
22+ }
2023
2124 abstract public function handleEmptyResponse (?string $ content = null , ?\Psr \Http \Message \ResponseInterface $ response = null );
2225
@@ -71,14 +74,42 @@ public function paginate()
7174 return $ paginate ;
7275 }
7376
74-
7577 public function __call ($ method , $ args )
7678 {
77- $ this ->response = $ this ->getHttpClient ()->$ method (...$ args );
79+ // 异步请求处理
80+ if (method_exists (\GuzzleHttp \Promise \Utils::class, $ method )) {
81+ $ results = call_user_func_array ([\GuzzleHttp \Promise \Utils::class, $ method ], $ args );
82+
83+ if (!is_array ($ results )) {
84+ return $ results ;
85+ }
7886
79- $ this ->result = $ this ->castResponse ($ this ->response );
87+ $ data = [];
88+ foreach ($ results as $ key => $ promise ) {
89+ $ data [$ key ] = $ this ->castResponse ($ promise );
90+ }
91+
92+ $ this ->attributes = $ data ;
93+
94+ return $ this ;
95+ }
8096
81- $ this ->attributes = $ this ->result ;
97+ // 同步请求
98+ if (method_exists ($ this ->getHttpClient (), $ method )) {
99+ $ this ->response = $ this ->getHttpClient ()->$ method (...$ args );
100+ }
101+
102+ // 响应结果处理
103+ if ($ this ->response instanceof \GuzzleHttp \Psr7 \Response) {
104+ $ this ->result = $ this ->castResponse ($ this ->response );
105+
106+ $ this ->attributes = $ this ->result ;
107+ }
108+
109+ // 将 promise 请求直接返回
110+ if ($ this ->response instanceof \GuzzleHttp \Promise \Promise) {
111+ return $ this ->response ;
112+ }
82113
83114 return $ this ;
84115 }
0 commit comments