Files
kiri-core/System/Channel.php
T

90 lines
1.5 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
{
private array $_channels = [];
/**
* @param mixed $value
* @param string $name
* @throws Exception
*/
2021-04-22 14:53:14 +08:00
public function push(mixed $value, string $name = ''): void
2021-03-26 15:59:39 +08:00
{
2021-04-22 14:49:32 +08:00
$channel = $this->channelInit($name);
2021-04-22 14:53:14 +08:00
$channel->enqueue($value);
2021-03-26 15:59:39 +08:00
}
/**
* @param string $name
2021-04-22 14:53:14 +08:00
* @return bool|SplQueue
2021-03-26 15:59:39 +08:00
*/
2021-04-22 14:49:32 +08:00
private function channelInit(string $name = ''): bool|SplQueue
2021-03-26 15:59:39 +08:00
{
2021-04-22 14:49:32 +08:00
if (!isset($this->_channels[$name]) || !($this->_channels[$name] instanceof SplQueue)) {
$this->_channels[$name] = new SplQueue();
2021-03-26 15:59:39 +08:00
}
2021-04-22 14:49:32 +08:00
return $this->_channels[$name];
2021-03-26 15:59:39 +08:00
}
2021-03-31 01:36:16 +08:00
/**
*
* 清空缓存
*/
public function cleanAll()
{
2021-04-22 14:49:32 +08:00
/** @var SplQueue $channel */
2021-03-31 01:36:16 +08:00
foreach ($this->_channels as $channel) {
2021-04-22 14:49:32 +08:00
while ($channel->count() > 0) {
$channel->dequeue();
}
2021-03-31 01:36:16 +08:00
}
$this->_channels = [];
}
2021-03-26 15:59:39 +08:00
/**
2021-03-29 14:02:16 +08:00
* @param $timeout
2021-03-29 13:58:15 +08:00
* @param Closure $closure
2021-03-26 15:59:39 +08:00
* @param string $name
* @return mixed
* @throws Exception
*/
2021-04-22 14:49:32 +08:00
public function pop(string $name, Closure $closure, int|float $timeout = null): mixed
2021-03-26 15:59:39 +08:00
{
2021-04-22 14:49:32 +08:00
if (($channel = $this->channelInit($name)) == false) {
2021-03-26 15:59:39 +08:00
return $this->addError('Channel is full.');
}
if (!$channel->isEmpty()) {
2021-03-29 17:47:13 +08:00
return $channel->pop();
}
2021-04-22 14:49:32 +08:00
if ($timeout !== null) {
2021-04-22 14:53:14 +08:00
$data = $channel->dequeue();
2021-04-22 14:49:32 +08:00
}
2021-03-29 14:02:16 +08:00
if (empty($data)) {
$data = call_user_func($closure);
2021-03-26 15:59:39 +08:00
}
2021-03-29 14:02:16 +08:00
return $data;
2021-03-26 15:59:39 +08:00
}
}