microphp/Core/Response.php

96 lines
3.2 KiB
PHP
Raw Normal View History

2023-04-02 10:00:20 +03:00
<?php
include_once "RequestHeader.php";
class Response
{
2023-04-11 00:30:15 +03:00
public static $mimes;
2023-04-02 10:00:20 +03:00
public static function File($path, $mime = "auto")
{
if($mime == "auto")
{
2023-04-11 00:30:15 +03:00
$exploder = explode(".", $path);
$ext = end($exploder);
$mime = Response::$mimes[$ext] ?? "application/octet-stream";
2023-04-02 10:00:20 +03:00
};
2023-04-11 00:30:15 +03:00
RequestHeader::set("Content-Type",$mime);
2023-04-07 01:02:39 +03:00
$fp = fopen($path, 'rb');
fpassthru($fp);
fclose($fp);
2023-04-02 10:00:20 +03:00
}
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));
2023-04-07 01:02:39 +03:00
$fp = fopen($path, 'rb');
fpassthru($fp);
fclose($fp);
2023-04-02 10:00:20 +03:00
}
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;
}
2023-04-11 22:59:27 +03:00
public static function html($content, $encoding = "utf8")
2023-04-02 10:00:20 +03:00
{
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);
}
2023-04-11 22:59:27 +03:00
public static function view(...$args)
{
Response::html(view(...$args));
}
2023-04-02 10:00:20 +03:00
public static function send($content)
{
switch(gettype($content))
{
case "boolean":
case "integer":
case "double":
case "float":
case "string":{
Response::Text($content);
break;
}
2023-04-02 18:07:52 +03:00
case "object":{
if(method_exists($content, "__toString"))
{
return Response::Text($content->__toString());
}else{
return Response::Json($content);
}
}
2023-04-02 10:00:20 +03:00
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");
}
2023-04-07 01:02:39 +03:00
};
define("response", new Response(), false);