77
88class Context
99{
10+ protected const MAX_RECURSE_COROUTINE_ID = 50 ;
11+
1012 /**
1113 * The app containers in different coroutine environment.
1214 *
@@ -26,7 +28,7 @@ class Context
2628 */
2729 public static function getApp ()
2830 {
29- return static ::$ apps [static ::getCoroutineId ()] ?? null ;
31+ return static ::$ apps [static ::getRequestedCoroutineId ()] ?? null ;
3032 }
3133
3234 /**
@@ -36,7 +38,7 @@ public static function getApp()
3638 */
3739 public static function setApp (Container $ app )
3840 {
39- static ::$ apps [static ::getCoroutineId ()] = $ app ;
41+ static ::$ apps [static ::getRequestedCoroutineId ()] = $ app ;
4042 }
4143
4244 /**
@@ -48,7 +50,7 @@ public static function setApp(Container $app)
4850 */
4951 public static function getData (string $ key )
5052 {
51- return static ::$ data [static ::getCoroutineId ()][$ key ] ?? null ;
53+ return static ::$ data [static ::getRequestedCoroutineId ()][$ key ] ?? null ;
5254 }
5355
5456 /**
@@ -59,7 +61,7 @@ public static function getData(string $key)
5961 */
6062 public static function setData (string $ key , $ value )
6163 {
62- static ::$ data [static ::getCoroutineId ()][$ key ] = $ value ;
64+ static ::$ data [static ::getRequestedCoroutineId ()][$ key ] = $ value ;
6365 }
6466
6567 /**
@@ -69,31 +71,46 @@ public static function setData(string $key, $value)
6971 */
7072 public static function removeData (string $ key )
7173 {
72- unset(static ::$ data [static ::getCoroutineId ()][$ key ]);
74+ unset(static ::$ data [static ::getRequestedCoroutineId ()][$ key ]);
7375 }
7476
7577 /**
7678 * Get data keys by current coroutine id.
7779 */
7880 public static function getDataKeys ()
7981 {
80- return array_keys (static ::$ data [static ::getCoroutineId ()] ?? []);
82+ return array_keys (static ::$ data [static ::getRequestedCoroutineId ()] ?? []);
8183 }
8284
8385 /**
8486 * Clear data by current coroutine id.
8587 */
8688 public static function clear ()
8789 {
88- unset(static ::$ apps [static ::getCoroutineId ()]);
89- unset(static ::$ data [static ::getCoroutineId ()]);
90+ unset(static ::$ apps [static ::getRequestedCoroutineId ()]);
91+ unset(static ::$ data [static ::getRequestedCoroutineId ()]);
92+ }
93+
94+ public static function getCoroutineId (): int
95+ {
96+ return Coroutine::getuid ();
9097 }
9198
9299 /**
93100 * Get current coroutine id.
94101 */
95- public static function getCoroutineId ()
102+ public static function getRequestedCoroutineId (): int
96103 {
97- return Coroutine::getuid ();
104+ $ currentId = static ::getCoroutineId ();
105+ if ($ currentId === -1 ) {
106+ return -1 ;
107+ }
108+
109+ $ counter = 0 ;
110+ while (($ topCoroutineId = Coroutine::getPcid ($ currentId )) !== -1 && $ counter <= static ::MAX_RECURSE_COROUTINE_ID ) {
111+ $ currentId = $ topCoroutineId ;
112+ $ counter ++;
113+ }
114+ return $ currentId ;
98115 }
99116}
0 commit comments