<?php
namespace Yurun\Util;
use Swoole\Coroutine;
use Yurun\Util\YurunHttp\Handler\IHandler;
abstract class YurunHttp
{
private static $defaultHandler = null;
private static $attributes = [];
const VERSION = '4.2';
public static function setDefaultHandler($class)
{
static::$defaultHandler = $class;
}
public static function getDefaultHandler()
{
return static::$defaultHandler;
}
public static function getHandler()
{
if(static::$defaultHandler)
{
$class = static::$defaultHandler;
}
if(defined('SWOOLE_VERSION') && Coroutine::getuid() > -1)
{
$class = \Yurun\Util\YurunHttp\Handler\Swoole::class;
}
else
{
$class = \Yurun\Util\YurunHttp\Handler\Curl::class;
}
return new $class;
}
public static function send($request, $handlerClass = null)
{
if($handlerClass instanceof IHandler)
{
$handler = $handlerClass;
}
else if(null === $handlerClass)
{
$handler = static::getHandler();
}
else
{
$handler = new $handlerClass();
}
$time = microtime(true);
foreach(static::$attributes as $name => $value)
{
if(null === $request->getAttribute($name))
{
$request = $request->withAttribute($name, $value);
}
}
$handler->send($request);
$response = $handler->recv();
if(!$response)
{
return $response;
}
$response = $response->withTotalTime(microtime(true) - $time);
return $response;
}
public static function websocket($request, $handlerClass = null)
{
if($handlerClass instanceof IHandler)
{
$handler = $handlerClass;
}
else if(null === $handlerClass)
{
$handler = static::getHandler();
}
else
{
$handler = new $handlerClass();
}
$time = microtime(true);
foreach(static::$attributes as $name => $value)
{
if(null === $request->getAttribute($name))
{
$request = $request->withAttribute($name, $value);
}
}
$websocketClient = $handler->websocket($request);
$response = $websocketClient->getHttpResponse()->withTotalTime(microtime(true) - $time);
$websocketClient->init($handler, $request, $response);
return $websocketClient;
}
public static function getAttributes()
{
return static::$attributes;
}
public static function getAttribute($name, $default = null)
{
if(array_key_exists($name, static::$attributes))
{
return static::$attributes[$name];
}
else
{
return $default;
}
}
public static function setAttribute($name, $value)
{
static::$attributes[$name] = $value;
}
}