Files
kiri-core/System/Channel.php
T

97 lines
1.8 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;
use Swoole\Coroutine\Channel as CChannel;
/**
* Class Channel
* @package Snowflake
*/
class Channel extends Component
{
private ?CChannel $_channel = null;
private array $_channels = [];
/**
* @param mixed $value
* @param string $name
* @param int $length
* @return mixed
* @throws Exception
*/
public function push(mixed $value, string $name = '', $length = 999): mixed
{
$channel = $this->channelInit($length, $name);
if ($channel->isFull()) {
return $this->addError('Channel is full.');
}
return $channel->push($value);
}
/**
* @param int $length
* @param string $name
* @return bool|CChannel
*/
private function channelInit(int $length, string $name = ''): bool|CChannel
{
if ($length < 1) {
return false;
}
if (empty($name)) {
if (!($this->_channel instanceof CChannel)
|| $this->_channel->close()) {
$this->_channel = new CChannel($length);
}
return $this->_channel;
} else {
if (!isset($this->_channels[$name]) || !($this->_channels[$name] instanceof CChannel)) {
$this->_channels[$name] = new CChannel($length);
} else if ($this->_channels[$name]->close()) {
$this->_channels[$name] = new CChannel($length);
}
return $this->_channels[$name];
}
}
/**
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
2021-03-29 14:02:16 +08:00
* @param int $length
2021-03-26 15:59:39 +08:00
* @return mixed
* @throws Exception
*/
2021-03-29 14:03:18 +08:00
public function pop(int|float $timeout, string $name, Closure $closure, int $length = 100): mixed
2021-03-26 15:59:39 +08:00
{
2021-03-29 14:02:16 +08:00
if (($channel = $this->channelInit($length, $name)) == false) {
2021-03-26 15:59:39 +08:00
return $this->addError('Channel is full.');
}
2021-03-29 14:02:16 +08:00
$data = null;
2021-03-26 15:59:39 +08:00
if (!$channel->isEmpty()) {
2021-03-29 14:02:16 +08:00
$data = $channel->pop($timeout);
}
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
}
}