Files
kiri-core/HttpServer/Events/Utility/DataResolve.php
T

93 lines
1.8 KiB
PHP
Raw Normal View History

2020-11-04 19:28:40 +08:00
<?php
namespace HttpServer\Events\Utility;
use Closure;
use Exception;
use ReflectionException;
use Snowflake\Core\JSON;
use Snowflake\Exception\NotFindClassException;
use Snowflake\Snowflake;
class DataResolve
{
/**
* @param $unpack
* @param $data
* @return mixed
* @throws NotFindClassException
* @throws ReflectionException
* @throws Exception
*/
public static function pack($unpack, $data)
{
if (empty($unpack)) {
2020-11-05 18:27:24 +08:00
$params = JSON::encode($data);
} else {
$params = self::callbackResolve($unpack, null, null, $data);
2020-11-04 19:28:40 +08:00
}
2020-11-05 18:27:24 +08:00
if ($params === null) {
return 'Format error.';
}
return $params;
2020-11-04 19:28:40 +08:00
}
/**
* @param $unpack
* @param $address
* @param $port
* @param $data
* @return mixed
* @throws NotFindClassException
* @throws ReflectionException
*/
public static function unpack($unpack, $address, $port, $data)
{
if (empty($unpack)) {
2020-11-05 18:27:24 +08:00
$params = JSON::decode($data);
} else {
$params = self::callbackResolve($unpack, $address, $port, $data);
}
if ($params === null) {
return 'Format error.';
2020-11-04 19:28:40 +08:00
}
2020-11-05 18:27:24 +08:00
return $params;
2020-11-04 19:28:40 +08:00
}
/**
* @param $callback
* @param $address
* @param $port
* @param $data
2020-12-17 14:09:14 +08:00
* @return mixed
2020-11-04 19:28:40 +08:00
* @throws NotFindClassException
* @throws ReflectionException
*/
2020-12-17 14:09:14 +08:00
private static function callbackResolve($callback, $address, $port, $data): mixed
2020-11-04 19:28:40 +08:00
{
if ($callback instanceof Closure) {
2020-11-05 18:32:59 +08:00
if (empty($address) && empty($port)) {
return $callback($data);
}
2020-11-04 19:28:40 +08:00
return $callback($address, $port, $data);
}
if (is_string($callback)) {
$callback = [$callback, 'onHandler'];
}
if (isset($callback[0]) && is_string($callback[0])) {
$callback[0] = Snowflake::getDi()->get($callback[0]);
}
if (!empty($address) && !empty($port)) {
return call_user_func($callback, $address, $port, $data);
}
return call_user_func($callback, $data);
}
}