| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129 |
- <?php
- /**
- * This file is part of webman.
- *
- * Licensed under The MIT License
- * For full copyright and license information, please see the MIT-LICENSE.txt
- * Redistributions of files must retain the above copyright notice.
- *
- * @author walkor<walkor@workerman.net>
- * @copyright walkor<walkor@workerman.net>
- * @link http://www.workerman.net/
- * @license http://www.opensource.org/licenses/mit-license.php MIT License
- */
- namespace Webman;
- use Fiber;
- use SplObjectStorage;
- use StdClass;
- use Swow\Coroutine;
- use WeakMap;
- use Workerman\Events\Revolt;
- use Workerman\Events\Swoole;
- use Workerman\Events\Swow;
- use Workerman\Worker;
- use function property_exists;
- /**
- * Class Context
- * @package Webman
- */
- class Context
- {
- /**
- * @var SplObjectStorage|WeakMap
- */
- protected static $objectStorage;
- /**
- * @var StdClass
- */
- protected static $object;
- /**
- * @return StdClass
- */
- protected static function getObject(): StdClass
- {
- if (!static::$objectStorage) {
- static::$objectStorage = class_exists(WeakMap::class) ? new WeakMap() : new SplObjectStorage();
- static::$object = new StdClass;
- }
- $key = static::getKey();
- if (!isset(static::$objectStorage[$key])) {
- static::$objectStorage[$key] = new StdClass;
- }
- return static::$objectStorage[$key];
- }
- /**
- * @return mixed
- */
- protected static function getKey()
- {
- switch (Worker::$eventLoopClass) {
- case Revolt::class:
- return Fiber::getCurrent();
- case Swoole::class:
- return \Swoole\Coroutine::getContext();
- case Swow::class:
- return Coroutine::getCurrent();
- }
- return static::$object;
- }
- /**
- * @param string|null $key
- * @return mixed
- */
- public static function get(string $key = null)
- {
- $obj = static::getObject();
- if ($key === null) {
- return $obj;
- }
- return $obj->$key ?? null;
- }
- /**
- * @param string $key
- * @param $value
- * @return void
- */
- public static function set(string $key, $value): void
- {
- $obj = static::getObject();
- $obj->$key = $value;
- }
- /**
- * @param string $key
- * @return void
- */
- public static function delete(string $key): void
- {
- $obj = static::getObject();
- unset($obj->$key);
- }
- /**
- * @param string $key
- * @return bool
- */
- public static function has(string $key): bool
- {
- $obj = static::getObject();
- return property_exists($obj, $key);
- }
- /**
- * @return void
- */
- public static function destroy(): void
- {
- unset(static::$objectStorage[static::getKey()]);
- }
- }
|