mc-cms-namelessmc/core/classes/Core/Session.php

87 lines
2.3 KiB
PHP
Raw Permalink Normal View History

<?php
/**
* Provides access to get/set/delete session data.
*
* @package NamelessMC\Core
* @author Samerton
* @version 2.0.0-pr8
* @license MIT
*/
class Session
{
/**
* "Flash" a session variable.
* The first time this is called, the variable is set, the second time it is retrieved + removed from session.
* Often used for temp success/error messages.
*
* @param string $name Contains the session variable name to flash on screen.
* @param string $string Contains the message to flash on the screen (optional).
* @return mixed Session variable if it exists, nothing if it is being set.
*/
public static function flash(string $name, string $string = '')
{
2021-12-07 22:14:12 -08:00
// If the session exists, display it on screen ("flash" it)
if (self::exists($name)) {
$session = self::get($name);
self::delete($name);
2021-12-07 22:14:12 -08:00
return $session;
}
2022-01-15 15:18:05 -08:00
// The session doesn't exist, set it as a variable now, so it can be "flashed" in the future
2022-01-15 15:18:05 -08:00
self::put($name, $string);
return null;
2020-12-13 19:38:04 +01:00
}
/**
2021-12-07 22:14:12 -08:00
* Check to see if a session exists.
*
2021-12-07 22:14:12 -08:00
* @param string $name Session variable name to check for.
*
* @return bool
*/
public static function exists(string $name): bool
{
2021-12-07 22:14:12 -08:00
return isset($_SESSION[$name]);
2020-12-13 19:38:04 +01:00
}
/**
* Get a session variable.
*
* @param string $name Contains the session variable name to retrieve.
2021-12-07 22:14:12 -08:00
*
* @return mixed Session variable.
*/
public static function get(string $name)
{
2020-12-13 19:38:04 +01:00
return $_SESSION[$name];
}
2021-12-07 22:14:12 -08:00
/**
* Delete a session variable.
*
2021-10-07 14:02:46 -07:00
* @param string $name Contains the session variable name to delete.
*/
public static function delete(string $name): void
{
2020-12-13 20:42:04 -08:00
if (self::exists($name)) {
2020-12-13 19:38:04 +01:00
unset($_SESSION[$name]);
}
}
/**
* Create a new session variable.
*
* TODO: specify mixed as $value type when minimum PHP version bumped to 8
*
* @param string $name Contains the session variable name that will be created.
* @param mixed $value Contains the variable value to store
*/
public static function put(string $name, $value): void
{
2021-12-07 22:14:12 -08:00
$_SESSION[$name] = $value;
2020-12-13 19:38:04 +01:00
}
}