Files
kiri-core/System/Channel.php
T

87 lines
1.6 KiB
PHP
Raw Normal View History

2021-03-26 15:59:39 +08:00
<?php
namespace Snowflake;
2021-03-29 13:58:15 +08:00
use Closure;
2021-03-26 15:59:39 +08:00
use Exception;
use Snowflake\Abstracts\Component;
2021-04-22 14:49:32 +08:00
use SplQueue;
2021-03-26 15:59:39 +08:00
/**
* Class Channel
* @package Snowflake
*/
class Channel extends Component
{
2021-05-07 17:06:10 +08:00
private static array $_channels = [];
2021-04-23 03:12:00 +08:00
/**
* @param mixed $value
* @param string $name
* @throws Exception
*/
public function push(mixed $value, string $name = ''): void
{
$channel = $this->channelInit($name);
2021-05-02 05:22:20 +08:00
if ($channel->count() >= 100) {
return;
}
2021-04-23 03:12:00 +08:00
$channel->enqueue($value);
}
/**
* @param string $name
* @return bool|SplQueue
*/
private function channelInit(string $name = ''): bool|SplQueue
{
2021-05-07 17:06:10 +08:00
if (!isset(static::$_channels[$name]) || !(static::$_channels[$name] instanceof SplQueue)) {
static::$_channels[$name] = new SplQueue();
2021-04-23 03:12:00 +08:00
}
2021-05-07 17:06:10 +08:00
return static::$_channels[$name];
2021-04-23 03:12:00 +08:00
}
/**
*
* 清空缓存
*/
public function cleanAll()
{
/** @var SplQueue $channel */
2021-05-07 17:06:10 +08:00
foreach (static::$_channels as $channel) {
2021-04-23 03:12:00 +08:00
if (!($channel instanceof SplQueue)) {
continue;
}
while ($channel->count() > 0) {
$channel->dequeue();
}
}
2021-05-07 17:06:10 +08:00
static::$_channels = [];
2021-04-23 03:12:00 +08:00
}
2021-05-07 17:06:10 +08:00
/**
* @param string $name
* @param Closure $closure
* @return mixed
*/
2021-05-02 04:46:21 +08:00
public function pop(string $name, Closure $closure): mixed
2021-04-23 03:12:00 +08:00
{
2021-05-02 05:29:32 +08:00
$channel = $this->channelInit($name);
2021-05-02 04:46:21 +08:00
if ($channel->isEmpty()) {
return call_user_func($closure);
2021-04-23 03:12:00 +08:00
}
2021-05-02 04:46:21 +08:00
return $channel->dequeue();
2021-04-23 03:12:00 +08:00
}
2021-03-26 15:59:39 +08:00
}