microphp/Core/Response.php

96 lines
3.2 KiB
PHP
Executable File

<?php
include_once "RequestHeader.php";
class Response
{
public static $mimes;
public static function File($path, $mime = "auto")
{
if($mime == "auto")
{
$exploder = explode(".", $path);
$ext = end($exploder);
$mime = Response::$mimes[$ext] ?? "application/octet-stream";
};
RequestHeader::set("Content-Type",$mime);
$fp = fopen($path, 'rb');
fpassthru($fp);
fclose($fp);
}
public static function Download($path, $mimetrue = false)
{
if($mimetrue == false)
{
RequestHeader::set("Content-Type","application/octet-stream");
}
RequestHeader::set("Content-Transfer-Encoding","Binary");
RequestHeader::set("Content-Disposition",'attachment; filename="'.basename($path).'"');
RequestHeader::set("Content-Length",filesize($path));
$fp = fopen($path, 'rb');
fpassthru($fp);
fclose($fp);
}
public static function Text($content, $encoding = "utf8")
{
RequestHeader::set("Content-Length",strlen($content));
RequestHeader::set("Content-Type","text/plain; charset=$encoding");
echo $content;
}
public static function Json($content, $encoding = "utf8")
{
$content = json_encode($content);
RequestHeader::set("Content-Length",strlen($content));
RequestHeader::set("Content-Type","application/json; charset=$encoding");
echo $content;
}
public static function html($content, $encoding = "utf8")
{
RequestHeader::set("Content-Length",strlen($content));
RequestHeader::set("Content-Type","text/html; charset=$encoding");
echo $content;
}
public static function Code($code = 200)
{
http_response_code($code);
}
public static function view(...$args)
{
Response::html(view(...$args));
}
public static function send($content)
{
switch(gettype($content))
{
case "boolean":
case "integer":
case "double":
case "float":
case "string":{
Response::Text($content);
break;
}
case "object":{
if(method_exists($content, "__toString"))
{
return Response::Text($content->__toString());
}else{
return Response::Json($content);
}
}
case "array":{
Response::Json($content);
break;
}
default:{
throw new Exception("unknown type");
}
}
}
public static function Redirect($path, $code = 307)
{
http_response_code($code);
header("location: $path");
}
};
define("response", new Response(), false);