diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f3db63..bc6993f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,25 @@ # Changelog +## v2.4.3 - 🎋 Giant Cane Grass - 26th February 2021 + +### Added + +- Updated `Leaf\Db` and `Leaf\Auth` to throw dev errors to Leaf's error handler for better error reporting + +### Fixed + +- Organized methods in `Leaf\FS` + +### Changed + +- Made `Leaf\Http\Response` static +- Made `Leaf\Http\Request` static + +### Removed + +- No removals + ## v2.4.2 - 🥬 Desert Wishbone-bush - 3rd February 2021 This version of Leaf continues the goal of making Leaf features more flexible and increasing usability. diff --git a/README.md b/README.md index 7f52ef2..fea80e2 100644 --- a/README.md +++ b/README.md @@ -38,16 +38,18 @@ $auth = new Leaf\Auth; $auth->connect("host", "user", "pass", "db name"); +// Base example $app->get('/', function() use($app) { $app->response()->respond("My first Leaf app"); }); +// Full login example $app->post('/auth/login', function() use($app, $auth) { $credentials = $app->request()->get(["username", "password"]); $user = $auth->login("users", $credentials, [ - "username" => ["username", "min:3"], - "password" => ["text", "NoSpaces"] + "username" => ["username", "max:15"], + "password" => ["text", "NoSpaces", "min:8"], ]); if (!$user) { diff --git a/composer.json b/composer.json index 0168cad..e7132ae 100644 --- a/composer.json +++ b/composer.json @@ -16,7 +16,7 @@ { "name": "Michael Darko", "email": "mickdd22@gmail.com", - "homepage": "https://mychi.netlify.com", + "homepage": "https://mychi.netlify.app", "role": "Developer" } ], diff --git a/src/Auth.php b/src/Auth.php index 458a7c9..ec63e25 100755 --- a/src/Auth.php +++ b/src/Auth.php @@ -284,9 +284,15 @@ public static function guard($type) { static::experimental("guard"); + if (is_array($type)) { + if (isset($type["hasAuth"])) { + $type = $type["hasAuth"] ? 'auth' : 'guest'; + } + } + if (!static::config("USE_SESSION")) { if ($type === 'guest' && static::user()) { - (new Http\Response)->throwErr("You can't view this page while you're logged in!"); + (new Http\Response)->throwErr(["auth" => "You can't view this page while you're logged in!"]); } if ($type === 'auth' && !static::user()) { @@ -294,12 +300,6 @@ public static function guard($type) } } - if (is_array($type)) { - if (isset($type["hasAuth"])) { - $type = $type["hasAuth"] ? 'auth' : 'guest'; - } - } - if ($type === 'guest' && static::session()) { exit(header("location: " . static::config("GUARD_HOME"), true, 302)); } @@ -525,7 +525,7 @@ public static function update(string $table, array $credentials, array $where, a if (count($uniques) > 0) { foreach ($uniques as $unique) { if (!isset($credentials[$unique])) { - (new Http\Response)->throwErr(["error" => "$unique not found in credentials."]); + trigger_error("$unique not found in credentials: " . json_encode($credentials)); } $data = static::$db->select($table)->where($unique, $credentials[$unique])->fetchAssoc(); diff --git a/src/Db.php b/src/Db.php index bac9417..220a4c8 100755 --- a/src/Db.php +++ b/src/Db.php @@ -57,11 +57,6 @@ class Db */ protected $form; - /** - * Leaf Response Module - */ - protected $response; - /** * List of methods called */ @@ -70,7 +65,6 @@ class Db public function __construct($host = null, $user = null, $password = null, $dbname = null) { $this->form = new Form; - $this->response = new Http\Response; if ($host != null || $user != null || $password != null || $dbname != null) { $this->connect($host, $user, $password, $dbname); @@ -535,7 +529,7 @@ public function bind(...$bindings): self public function execute($paramTypes = null) { if ($this->connection === null) { - $this->response->throwErr("Couldn't establish database connection. Call the connect() method, or check your database"); + trigger_error("Couldn't establish database connection. Call the connect() method, or check your database"); } if (count($this->errorsArray) > 0) return null; @@ -561,7 +555,7 @@ public function execute($paramTypes = null) if (count($uniques) > 0 && ($this->queryData["type"] != "select" || $this->queryData["type"] != "delete")) { foreach ($uniques as $unique) { if (!isset($paramValues[$unique])) { - $this->response->throwErr(["error" => "$unique not found, Add $unique to your \$db->add items or check your spelling."]); + trigger_error("$unique not found, Add $unique to your \$db->add items or check your spelling."); } if (mysqli_fetch_object($this->connection->query("SELECT * FROM {$this->queryData["table"]} WHERE $unique = '$paramValues[$unique]'"))) { diff --git a/src/FS.php b/src/FS.php index 446a570..466b507 100755 --- a/src/FS.php +++ b/src/FS.php @@ -111,36 +111,6 @@ public static function listDir($dirname, $pattern = null) return $filenames; } - /** - * Get an array of all files in a directory. - * - * @param string $directory - * @param bool $hidden - * @return \Symfony\Component\Finder\SplFileInfo[] - */ - public static function listFiles($directory, $hidden = false) - { - return iterator_to_array( - Finder::create()->files()->ignoreDotFiles(!$hidden)->in($directory)->depth(0)->sortByName(), - false - ); - } - - /** - * Get all of the files from the given directory (recursive). - * - * @param string $directory - * @param bool $hidden - * @return \Symfony\Component\Finder\SplFileInfo[] - */ - public static function allFiles($directory, $hidden = false) - { - return iterator_to_array( - Finder::create()->files()->ignoreDotFiles(!$hidden)->in($directory)->sortByName(), - false - ); - } - /** * Get all of the directories within a given directory. * @@ -177,103 +147,6 @@ public static function createFile($filename) touch($filename); } - /** - * Upload a file - * - * @param string $file The file to upload - * @param string $path The path to save the file in - * @param string $file_category The type of file - * @param array $config Configuration options for file upload - * - * @return string|bool - */ - public static function uploadFile($file, $path, $config = []) - { - if (!is_dir($path)) { - if (isset($config["verify_dir"]) && $config["verify_dir"] == true) { - self::$errorsArray["upload"] = "Specified path '$path' does not exist"; - return false; - } else { - mkdir($path, 0777, true); - } - } - - if (isset($config["unique"]) && $config["unique"] == true) { - $name = strtolower(strtotime(date("Y-m-d H:i:s")) . '_' . str_replace(" ", "_", $file["name"])); - } else { - $name = str_replace(" ", "_", $file["name"]); - } - - $temp = $file["tmp_name"]; - $size = $file["size"]; - $target_dir = $path; - $target_file = $target_dir . basename($name); - - if (file_exists($target_file) && (isset($config["verify_file"]) && $config["verify_file"] == true)) { - self::$errorsArray["upload"] = "$target_file already exists"; - return false; - } - - $file_type = strtolower(pathinfo($target_file, PATHINFO_EXTENSION)); - $maximum_file_size = $config["max_file_size"] ?? 10000000; - $file_category = $config["file_type"] ?? self::getCategory($file_type); - - if ($size > $maximum_file_size) { - self::$errorsArray["upload"] = "maximum file exceeded, please choose a file smaller than 10mb"; - return false; - } - - if (isset($config["validate"]) && $config["validate"] == true) { - foreach (self::$extensions as $category => $exts) { - if ($file_category == $category) $extensions = $exts; - } - - if (!in_array($file_type, $extensions)) { - self::$errorsArray["upload"] = $file['name'] . " format not acceptable for $file_category"; - return false; - } - } - - self::$uploadInfo[$name] = [ - "name" => $name, - "size" => $size, - "type" => $file_type, - "category" => $file_category, - "path" => $target_file, - "parent_directory" => basename(dirname($target_file)), - "parent_directory_path" => $target_dir - ]; - - if (move_uploaded_file($temp, $target_file)) { - return $name; - } else { - self::$errorsArray["upload"] = "Wasn't able to upload $file_category"; - return false; - } - } - - /** - * Get full information about an uploaded file - * - * @param string|null $file The file info to get - */ - public static function uploadInfo($file = null): array - { - return $file ? self::$uploadInfo[$file] : self::$uploadInfo; - } - - /** - * Get a file category from it's extension - */ - protected static function getCategory(string $file_type) - { - foreach (self::$extensions as $category => $exts) { - if (in_array($file_type, $exts)) return $category; - } - - return 'file'; - } - /** * Write content to a file * @@ -321,6 +194,7 @@ public static function renameFile($filename, $newfilename) self::$errorsArray[$filename] = "$filename not found in " . dirname($filename); return false; } + rename($filename, $newfilename); } @@ -337,6 +211,7 @@ public static function deleteFile($filename) self::$errorsArray[$filename] = "$filename not found in " . dirname($filename); return false; } + unlink($filename); } @@ -355,10 +230,13 @@ public static function copyFile($filename, $to, $rename = true) self::$errorsArray[$filename] = "$filename not found in " . dirname($filename); return false; } + $newfilename = $filename; + if (file_exists($filename) && $rename == true) { $newfilename = "(" . time() . ")" . $filename; } + try { copy($filename, $to . "/" . $newfilename); return $newfilename; @@ -437,6 +315,133 @@ public static function superCopy($source, $dest, $permissions = 0755) return true; } + /** + * Get an array of all files in a directory. + * + * @param string $directory + * @param bool $hidden + * @return \Symfony\Component\Finder\SplFileInfo[] + */ + public static function listFiles($directory, $hidden = false) + { + return iterator_to_array( + Finder::create()->files()->ignoreDotFiles(!$hidden)->in($directory)->depth(0)->sortByName(), + false + ); + } + + /** + * Get all of the files from the given directory (recursive). + * + * @param string $directory + * @param bool $hidden + * @return \Symfony\Component\Finder\SplFileInfo[] + */ + public static function allFiles($directory, $hidden = false) + { + return iterator_to_array( + Finder::create()->files()->ignoreDotFiles(!$hidden)->in($directory)->sortByName(), + false + ); + } + + /** + * Upload a file + * + * @param string $file The file to upload + * @param string $path The path to save the file in + * @param string $file_category The type of file + * @param array $config Configuration options for file upload + * + * @return string|bool + */ + public static function uploadFile($file, $path, $config = []) + { + if (!is_dir($path)) { + if (isset($config["verify_dir"]) && $config["verify_dir"] == true) { + self::$errorsArray["upload"] = "Specified path '$path' does not exist"; + return false; + } else { + mkdir($path, 0777, true); + } + } + + if (isset($config["unique"]) && $config["unique"] == true) { + $name = strtolower(strtotime(date("Y-m-d H:i:s")) . '_' . str_replace(" ", "_", $file["name"])); + } else { + $name = str_replace(" ", "_", $file["name"]); + } + + $temp = $file["tmp_name"]; + $size = $file["size"]; + $target_dir = $path; + $target_file = $target_dir . basename($name); + + if (file_exists($target_file) && (isset($config["verify_file"]) && $config["verify_file"] == true)) { + self::$errorsArray["upload"] = "$target_file already exists"; + return false; + } + + $file_type = strtolower(pathinfo($target_file, PATHINFO_EXTENSION)); + $maximum_file_size = $config["max_file_size"] ?? 10000000; + $file_category = $config["file_type"] ?? self::getCategory($file_type); + + if ($size > $maximum_file_size) { + self::$errorsArray["upload"] = "maximum file exceeded, please choose a file smaller than 10mb"; + return false; + } + + if (isset($config["validate"]) && $config["validate"] == true) { + foreach (self::$extensions as $category => $exts) { + if ($file_category == $category) $extensions = $exts; + } + + if (!in_array($file_type, $extensions)) { + self::$errorsArray["upload"] = $file['name'] . " format not acceptable for $file_category"; + return false; + } + } + + self::$uploadInfo[$name] = [ + "name" => $name, + "size" => $size, + "type" => $file_type, + "category" => $file_category, + "path" => $target_file, + "parent_directory" => basename(dirname($target_file)), + "parent_directory_path" => $target_dir + ]; + + if (move_uploaded_file($temp, $target_file)) { + return $name; + } else { + self::$errorsArray["upload"] = "Wasn't able to upload $file_category"; + return false; + } + } + + /** + * Get full information about an uploaded file + * + * @param string|null $file The file info to get + */ + public static function uploadInfo($file = null): array + { + return $file ? self::$uploadInfo[$file] : self::$uploadInfo; + } + + /** + * Get a file category from it's extension + */ + protected static function getCategory(string $file_type) + { + foreach (self::$extensions as $category => $exts) { + if (in_array($file_type, $exts)) return $category; + } + + return 'file'; + } + public static function hashDirectory($directory) { if (!is_dir($directory)) { diff --git a/src/Form.php b/src/Form.php index 1618e8c..bdce5ad 100755 --- a/src/Form.php +++ b/src/Form.php @@ -182,10 +182,9 @@ public static function sanitizeInput($data) public static function validate(array $rules, array $messages = []) { $fields = []; - $req = new Request; foreach ($rules as $param => $rule) { - array_push($fields, ["name" => $param, "value" => $req->get($param), "rule" => $rule]); + array_push($fields, ["name" => $param, "value" => Request::get($param), "rule" => $rule]); } foreach ($fields as $field) { @@ -213,8 +212,6 @@ public static function validate(array $rules, array $messages = []) */ public static function validateData(array $rules, array $messages = []) { - $supportedRules = static::supportedRules(); - $fields = []; foreach ($rules as $param => $rule) { @@ -291,7 +288,7 @@ public static function isEmail($value) */ public static function body() { - return (new Request)->body(); + return Request::body(); } /** @@ -301,7 +298,7 @@ public static function body() */ public static function get() { - return (new Request)->body(); + return Request::body(); } /** diff --git a/src/Http/Request.php b/src/Http/Request.php index ee363bc..f69331e 100755 --- a/src/Http/Request.php +++ b/src/Http/Request.php @@ -4,9 +4,11 @@ /** * Leaf HTTP Request + * -------- * - * This class provides a human-friendly interface to the Leaf environment variables; - * environment variables are passed by reference and will be modified directly. + * This class provides an object-oriented way to interact with the current + * HTTP request being handled by your application as well as retrieve the input, + * cookies, and files that were submitted with the request. * * @author Michael Darko * @since 1.0.0 @@ -31,38 +33,38 @@ class Request * Application Environment * @var \Leaf\Environment */ - protected $env; + protected static $env; /** * HTTP Headers * @var \Leaf\Http\Headers */ - public $headers; + public static $headers; /** * HTTP Cookies * @var \Leaf\Helpers\Set */ - public $cookies; + public static $cookies; /** * The Request Body */ - protected $request; + protected static $request; public function __construct() { - $this->env = new \Leaf\Environment(); + static::$env = new \Leaf\Environment(); $handler = fopen('php://input', 'r'); - $this->request = stream_get_contents($handler); - $this->headers = new Headers(); + static::$request = stream_get_contents($handler); + static::$headers = new Headers(); } /** * Get HTTP method * @return string */ - public function getMethod() + public static function getMethod() { return $_SERVER['REQUEST_METHOD']; } @@ -73,9 +75,9 @@ public function getMethod() * @param string $type The type of request to check for * @return bool */ - public function typeIs(string $type) + public static function typeIs(string $type) { - return $this->getMethod() === strtoupper($type); + return static::getMethod() === strtoupper($type); } /** @@ -84,19 +86,19 @@ public function typeIs(string $type) * @param string $header Header to check for * @return bool */ - public function hasHeader(String $header) + public static function hasHeader(String $header) { - return !!$this->headers->get($header); + return !!static::$headers->get($header); } /** * Is this an AJAX request? * @return bool */ - public function isAjax() + public static function isAjax() { - if ($this->params('isajax')) return true; - if ($this->headers->get('X_REQUESTED_WITH') && $this->headers->get('X_REQUESTED_WITH') === 'XMLHttpRequest') return true; + if (static::params('isajax')) return true; + if (static::$headers->get('X_REQUESTED_WITH') && static::$headers->get('X_REQUESTED_WITH') === 'XMLHttpRequest') return true; return false; } @@ -105,9 +107,9 @@ public function isAjax() * Is this an XHR request? (alias of Leaf_Http_Request::isAjax) * @return bool */ - public function isXhr() + public static function isXhr() { - return $this->isAjax(); + return static::isAjax(); } /** @@ -122,9 +124,9 @@ public function isXhr() * * @return array|mixed|null */ - public function params($key = null, $default = null) + public static function params($key = null, $default = null) { - $union = $this->body(); + $union = static::body(); if ($key) return isset($union[$key]) ? $union[$key] : $default; return $union; @@ -140,13 +142,13 @@ public function params($key = null, $default = null) * @param string|array $params The parameter(s) to return * @param bool $safeData Sanitize output */ - public function get($params, bool $safeData = true) + public static function get($params, bool $safeData = true) { - if (is_string($params)) return $this->body($safeData)[$params] ?? null; + if (is_string($params)) return static::body($safeData)[$params] ?? null; $data = []; foreach ($params as $param) { - $data[$param] = $this->get($param, $safeData); + $data[$param] = static::get($param, $safeData); } return $data; } @@ -156,9 +158,9 @@ public function get($params, bool $safeData = true) * * @param bool $safeData Sanitize output */ - public function body(bool $safeData = true) + public static function body(bool $safeData = true) { - $req = is_array(json_decode($this->request, true)) ? json_decode($this->request, true) : []; + $req = is_array(json_decode(static::$request, true)) ? json_decode(static::$request, true) : []; return $safeData ? \Leaf\Util::sanitize(array_merge($_GET, $_FILES, $_POST, $req)) : array_merge($_GET, $_FILES, $_POST, $req); } @@ -167,7 +169,7 @@ public function body(bool $safeData = true) * * @param string|array $filenames The file(s) you want to get */ - public function files($filenames = null) + public static function files($filenames = null) { if ($filenames == null) return $_FILES; if (is_string($filenames)) return $_FILES[$filenames] ?? null; @@ -188,7 +190,7 @@ public function files($filenames = null) * @param string $key * @return array|string|null */ - public function cookies($key = null) + public static function cookies($key = null) { return $key ? \Leaf\Http\Cookie::get($key) : \Leaf\Http\Cookie::all(); } @@ -197,11 +199,11 @@ public function cookies($key = null) * Does the Request body contain parsed form data? * @return bool */ - public function isFormData() + public static function isFormData() { - $method = $this->env['leaf.method_override.original_method'] ?? $this->getMethod(); + $method = static::$env['leaf.method_override.original_method'] ?? static::getMethod(); - return ($method === self::METHOD_POST && is_null($this->getContentType())) || in_array($this->getMediaType(), self::$formDataMediaTypes); + return ($method === self::METHOD_POST && is_null(static::getContentType())) || in_array(static::getMediaType(), self::$formDataMediaTypes); } /** @@ -215,28 +217,28 @@ public function isFormData() * * @return mixed */ - public function headers($key = null, $safeData = true) + public static function headers($key = null, $safeData = true) { - if ($key) return $this->headers->get($key, $safeData); - return $this->headers->all($safeData); + if ($key) return static::$headers->get($key, $safeData); + return static::$headers->all($safeData); } /** * Get Content Type * @return string|null */ - public function getContentType() + public static function getContentType() { - return $this->headers->get('CONTENT_TYPE'); + return static::$headers->get('CONTENT_TYPE'); } /** * Get Media Type (type/subtype within Content Type header) * @return string|null */ - public function getMediaType() + public static function getMediaType() { - $contentType = $this->getContentType(); + $contentType = static::getContentType(); if ($contentType) { $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType); @@ -250,9 +252,9 @@ public function getMediaType() * Get Media Type Params * @return array */ - public function getMediaTypeParams() + public static function getMediaTypeParams() { - $contentType = $this->getContentType(); + $contentType = static::getContentType(); $contentTypeParams = array(); if ($contentType) { $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType); @@ -270,9 +272,9 @@ public function getMediaTypeParams() * Get Content Charset * @return string|null */ - public function getContentCharset() + public static function getContentCharset() { - $mediaTypeParams = $this->getMediaTypeParams(); + $mediaTypeParams = static::getMediaTypeParams(); if (isset($mediaTypeParams['charset'])) { return $mediaTypeParams['charset']; } @@ -284,97 +286,97 @@ public function getContentCharset() * Get Content-Length * @return int */ - public function getContentLength() + public static function getContentLength() { - return $this->headers->get('CONTENT_LENGTH') ?? 0; + return static::$headers->get('CONTENT_LENGTH') ?? 0; } /** * Get Host * @return string */ - public function getHost() + public static function getHost() { - if (isset($this->env['HTTP_HOST'])) { - if (preg_match('/^(\[[a-fA-F0-9:.]+\])(:\d+)?\z/', $this->env['HTTP_HOST'], $matches)) { + if (isset(static::$env['HTTP_HOST'])) { + if (preg_match('/^(\[[a-fA-F0-9:.]+\])(:\d+)?\z/', static::$env['HTTP_HOST'], $matches)) { return $matches[1]; } else { - if (strpos($this->env['HTTP_HOST'], ':') !== false) { - $hostParts = explode(':', $this->env['HTTP_HOST']); + if (strpos(static::$env['HTTP_HOST'], ':') !== false) { + $hostParts = explode(':', static::$env['HTTP_HOST']); return $hostParts[0]; } } - return $this->env['HTTP_HOST']; + return static::$env['HTTP_HOST']; } - return $this->env['SERVER_NAME']; + return static::$env['SERVER_NAME']; } /** * Get Host with Port * @return string */ - public function getHostWithPort() + public static function getHostWithPort() { - return sprintf('%s:%s', $this->getHost(), $this->getPort()); + return sprintf('%s:%s', static::getHost(), static::getPort()); } /** * Get Port * @return int */ - public function getPort() + public static function getPort() { - return (int) $this->env['SERVER_PORT']; + return (int) static::$env['SERVER_PORT']; } /** * Get Scheme (https or http) * @return string */ - public function getScheme() + public static function getScheme() { - return $this->env['leaf.url_scheme']; + return static::$env['leaf.url_scheme']; } /** * Get Script Name (physical path) * @return string */ - public function getScriptName() + public static function getScriptName() { - return $this->env['SCRIPT_NAME']; + return static::$env['SCRIPT_NAME']; } /** * Get Path (physical path + virtual path) * @return string */ - public function getPath() + public static function getPath() { - return $this->getScriptName() . $this->getPathInfo(); + return static::getScriptName() . static::getPathInfo(); } /** * Get Path Info (virtual path) * @return string */ - public function getPathInfo() + public static function getPathInfo() { - return $this->env['PATH_INFO']; + return static::$env['PATH_INFO']; } /** * Get URL (scheme + host [ + port if non-standard ]) * @return string */ - public function getUrl() + public static function getUrl() { - $url = $this->getScheme() . '://' . $this->getHost(); - if (($this->getScheme() === 'https' && $this->getPort() !== 443) || ($this->getScheme() === 'http' && $this->getPort() !== 80)) { - $url .= ":{$this->getPort()}"; + $url = static::getScheme() . '://' . static::getHost(); + if ((static::getScheme() === 'https' && static::getPort() !== 443) || (static::getScheme() === 'http' && static::getPort() !== 80)) { + $url .= ":{static::getPort()}"; } return $url; @@ -384,42 +386,42 @@ public function getUrl() * Get IP * @return string */ - public function getIp() + public static function getIp() { $keys = array('X_FORWARDED_FOR', 'HTTP_X_FORWARDED_FOR', 'CLIENT_IP', 'REMOTE_ADDR'); foreach ($keys as $key) { - if (isset($this->env[$key])) { - return $this->env[$key]; + if (isset(static::$env[$key])) { + return static::$env[$key]; } } - return $this->env['REMOTE_ADDR']; + return static::$env['REMOTE_ADDR']; } /** * Get Referrer * @return string|null */ - public function getReferrer() + public static function getReferrer() { - return $this->headers->get('HTTP_REFERER'); + return static::$headers->get('HTTP_REFERER'); } /** * Get Referer (for those who can't spell) * @return string|null */ - public function getReferer() + public static function getReferer() { - return $this->getReferrer(); + return static::getReferrer(); } /** * Get User Agent * @return string|null */ - public function getUserAgent() + public static function getUserAgent() { - return $this->headers->get('HTTP_USER_AGENT'); + return static::$headers->get('HTTP_USER_AGENT'); } } diff --git a/src/Http/Response.php b/src/Http/Response.php index ac6b181..078a1d4 100755 --- a/src/Http/Response.php +++ b/src/Http/Response.php @@ -3,8 +3,8 @@ namespace Leaf\Http; /** - * Response - * -------------- + * Leaf HTTP Response + * ----------- * This is a simple abstraction over top an HTTP response. This * provides methods to set the HTTP status, the HTTP headers, * and the HTTP body. @@ -17,12 +17,12 @@ class Response /** * @var int HTTP status code */ - protected $status; + protected static $status; /** * @var \Leaf\Http\Headers */ - public $headers; + public static $headers; /** * @var array HTTP response codes and messages @@ -89,7 +89,7 @@ class Response public function __construct() { - $this->headers = new Headers; + static::$headers = new Headers; Headers::contentHtml(); } @@ -101,7 +101,7 @@ public function __construct() * @param bool $showCode Show response code in body? * @param bool $useMessage Show message instead of code */ - public function json($data, int $code = 200, bool $showCode = false, bool $useMessage = false) + public static function json($data, int $code = 200, bool $showCode = false, bool $useMessage = false) { if ($showCode) { $dataToPrint = ["data" => $data, "code" => $code]; @@ -120,7 +120,7 @@ public function json($data, int $code = 200, bool $showCode = false, bool $useMe /** * Throw an error and break the application */ - public function throwErr($error, int $code = 500, bool $useMessage = false) + public static function throwErr($error, int $code = 500, bool $useMessage = false) { $dataToPrint = ["error" => $error, "code" => $code]; if ($useMessage) $dataToPrint = ["error" => $error, "message" => isset(self::$messages[$code]) ? self::$messages[$code] : $code]; @@ -130,13 +130,13 @@ public function throwErr($error, int $code = 500, bool $useMessage = false) exit(); } - public function page(string $file, int $code = null) + public static function page(string $file, int $code = null) { Headers::contentHtml($code); require $file; } - public function markup(String $markup, int $code = null) + public static function markup(String $markup, int $code = null) { Headers::contentHtml($code); echo << $allow_origin, "Allow-Headers" => $allow_headers]); } @@ -156,7 +156,7 @@ public function cors(String $allow_origin = "*", String $allow_headers = "*") * @param string|null $value Header value * @return string Header value */ - public function header($name, $value = null) + public static function header($name, $value = null) { if (!is_null($value)) Headers::set($name, $value); return Headers::get($name); @@ -165,7 +165,7 @@ public function header($name, $value = null) /** * Set HTTP status code */ - public function status($code = null) + public static function status($code = null) { return Headers::status($code); } @@ -179,7 +179,7 @@ public function status($code = null) * @param string $value If string, the value of cookie * @param array $options Settings for cookie */ - public function setCookie($name, $value, $options = []) + public static function setCookie($name, $value, $options = []) { Cookie::set($name, $value, $options); } @@ -191,7 +191,7 @@ public function setCookie($name, $value, $options = []) * @param string $value The value of cookie * @param string $expire When the cookie expires. Default: 7 days */ - public function simpleCookie($name, $value, $expire = "7 days") + public static function simpleCookie($name, $value, $expire = "7 days") { Cookie::simpleCookie($name, $value, $expire); } @@ -201,7 +201,7 @@ public function simpleCookie($name, $value, $expire = "7 days") * * @param string $name The name of the cookie */ - public function deleteCookie($name) + public static function deleteCookie($name) { Cookie::unset($name); } @@ -215,7 +215,7 @@ public function deleteCookie($name) * @param string $url The redirect destination * @param int $status The redirect HTTP status code */ - public function redirect($url, $status = 302) + public static function redirect($url, $status = 302) { Headers::status($status); Headers::set('Location', $url); diff --git a/src/Http/Session.php b/src/Http/Session.php index d3d6e76..febf49e 100755 --- a/src/Http/Session.php +++ b/src/Http/Session.php @@ -155,7 +155,7 @@ public static function destroy() * * @param string $id: id to override the default * - * @return void + * @return false|void */ public static function reset($id = null) { @@ -163,6 +163,7 @@ public static function reset($id = null) static::$errorsArray["session"] = "No active session found!"; return false; } + session_reset(); static::set("id", $id ?? session_id()); } @@ -172,7 +173,7 @@ public static function reset($id = null) * * @param string [optional] $id: id to override the default * - * @return string: session id + * @return string */ public static function id($id = null) { @@ -185,7 +186,7 @@ public static function id($id = null) * * @param bool $clearData: Clear all session data? * - * @return void + * @return bool True on success, false on failure */ public static function regenerate($clearData = false) { @@ -194,6 +195,8 @@ public static function regenerate($clearData = false) /** * Encodes the current session data as a string + * + * @return string */ public static function encode(): string { @@ -202,6 +205,8 @@ public static function encode(): string /** * Decodes session data from a string + * + * @return bool */ public static function decode($data) { diff --git a/src/Util.php b/src/Util.php index 8bee1ef..d9cd68a 100755 --- a/src/Util.php +++ b/src/Util.php @@ -21,6 +21,7 @@ public static function sanitize($data) } else { $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8'); } + return $data; } }