Files
kiri-container/Context/CoroutineContext.php
T

93 lines
2.1 KiB
PHP
Raw Normal View History

2023-04-03 11:08:11 +08:00
<?php
2023-04-16 01:45:33 +08:00
declare(strict_types=1);
2023-04-03 11:08:11 +08:00
namespace Kiri\Di\Context;
use Swoole\Coroutine;
class CoroutineContext implements ContextInterface
{
2023-12-12 18:03:08 +08:00
/**
* @return bool
*/
public static function inCoroutine(): bool
{
2024-11-06 21:41:43 +08:00
return Coroutine::getCid() > -1;
2023-12-12 18:03:08 +08:00
}
2023-04-03 11:08:11 +08:00
2023-12-12 18:03:08 +08:00
/**
* @param string $key
* @param mixed $value
* @param int|null $coroutineId
* @return mixed
*/
public static function set(string $key, mixed $value, ?int $coroutineId = null): mixed
{
2024-11-06 21:41:43 +08:00
return Coroutine::getContext()[$key] = $value;
2023-12-12 18:03:08 +08:00
}
2023-04-03 11:08:11 +08:00
2023-12-12 18:03:08 +08:00
/**
* @param string $key
* @param mixed|null $defaultValue
* @param int|null $coroutineId
* @return mixed
*/
public static function get(string $key, mixed $defaultValue = null, ?int $coroutineId = null): mixed
{
2024-11-06 21:41:43 +08:00
return Coroutine::getContext()[$key] ?? $defaultValue;
2023-12-12 18:03:08 +08:00
}
2023-04-03 11:08:11 +08:00
2023-12-12 18:03:08 +08:00
/**
* @param string $key
* @param int|null $coroutineId
* @return mixed
*/
public static function exists(string $key, ?int $coroutineId = null): bool
{
2024-11-06 21:41:43 +08:00
return isset(Coroutine::getContext()[$key]);
2023-12-12 18:03:08 +08:00
}
2023-04-03 11:08:11 +08:00
2023-12-12 18:03:08 +08:00
/**
* @param string $key
* @param int|null $coroutineId
* @return void
*/
public static function remove(string $key, ?int $coroutineId = null): void
{
2024-11-06 21:41:43 +08:00
Coroutine::getContext()[$key] = null;
unset(Coroutine::getContext()[$key]);
2023-12-12 18:03:08 +08:00
}
2023-04-03 11:08:11 +08:00
2023-12-12 18:03:08 +08:00
/**
* @param string $id
* @param int $value
* @param int|null $coroutineId
* @return int
*/
public static function increment(string $id, int $value = 1, ?int $coroutineId = null): int
{
2024-11-06 21:41:43 +08:00
if (!isset(Coroutine::getContext()[$id])) {
Coroutine::getContext()[$id] = 0;
2023-12-12 18:03:08 +08:00
}
2024-11-06 21:41:43 +08:00
return Coroutine::getContext()[$id] += $value;
2023-12-12 18:03:08 +08:00
}
/**
* @param string $id
* @param int $value
* @param int|null $coroutineId
* @return int
*/
public static function decrement(string $id, int $value = 1, ?int $coroutineId = null): int
{
2024-11-06 21:41:43 +08:00
if (!isset(Coroutine::getContext()[$id])) {
Coroutine::getContext()[$id] = 0;
2023-12-12 18:03:08 +08:00
}
2024-11-06 21:41:43 +08:00
return Coroutine::getContext()[$id] -= $value;
2023-12-12 18:03:08 +08:00
}
2023-04-03 11:08:11 +08:00
}