93 lines
2.1 KiB
PHP
93 lines
2.1 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace Kiri\Di\Context;
|
|
|
|
use Swoole\Coroutine;
|
|
|
|
class CoroutineContext implements ContextInterface
|
|
{
|
|
|
|
|
|
/**
|
|
* @return bool
|
|
*/
|
|
public static function inCoroutine(): bool
|
|
{
|
|
return Coroutine::getCid() > -1;
|
|
}
|
|
|
|
|
|
/**
|
|
* @param string $key
|
|
* @param mixed $value
|
|
* @param int|null $coroutineId
|
|
* @return mixed
|
|
*/
|
|
public static function set(string $key, mixed $value, ?int $coroutineId = null): mixed
|
|
{
|
|
return Coroutine::getContext()[$key] = $value;
|
|
}
|
|
|
|
/**
|
|
* @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
|
|
{
|
|
return Coroutine::getContext()[$key] ?? $defaultValue;
|
|
}
|
|
|
|
/**
|
|
* @param string $key
|
|
* @param int|null $coroutineId
|
|
* @return mixed
|
|
*/
|
|
public static function exists(string $key, ?int $coroutineId = null): bool
|
|
{
|
|
return isset(Coroutine::getContext()[$key]);
|
|
}
|
|
|
|
/**
|
|
* @param string $key
|
|
* @param int|null $coroutineId
|
|
* @return void
|
|
*/
|
|
public static function remove(string $key, ?int $coroutineId = null): void
|
|
{
|
|
Coroutine::getContext()[$key] = null;
|
|
unset(Coroutine::getContext()[$key]);
|
|
}
|
|
|
|
|
|
/**
|
|
* @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
|
|
{
|
|
if (!isset(Coroutine::getContext()[$id])) {
|
|
Coroutine::getContext()[$id] = 0;
|
|
}
|
|
return Coroutine::getContext()[$id] += $value;
|
|
}
|
|
|
|
/**
|
|
* @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
|
|
{
|
|
if (!isset(Coroutine::getContext()[$id])) {
|
|
Coroutine::getContext()[$id] = 0;
|
|
}
|
|
return Coroutine::getContext()[$id] -= $value;
|
|
}
|
|
}
|