2022-01-15 10:26:02 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
// Handles anything to do with sessions
|
|
|
|
class Session
|
|
|
|
{
|
|
|
|
public function __construct()
|
|
|
|
{
|
2022-01-20 21:23:21 +00:00
|
|
|
// Start new session if there is none
|
2022-01-15 10:26:02 +00:00
|
|
|
if (session_status() === PHP_SESSION_NONE)
|
|
|
|
{
|
|
|
|
session_start();
|
|
|
|
}
|
|
|
|
}
|
2022-01-23 21:56:36 +00:00
|
|
|
|
|
|
|
public function has(string $key): bool
|
|
|
|
{
|
|
|
|
return array_key_exists($key, $_SESSION);
|
|
|
|
}
|
|
|
|
|
2022-01-24 08:00:22 +00:00
|
|
|
// Returns mixed but php 7.4 DOES NOT SUPPORT THAT TYPE HINT >:((
|
|
|
|
public function get(string $key)
|
2022-01-23 21:56:36 +00:00
|
|
|
{
|
|
|
|
if ($this->has($key))
|
|
|
|
{
|
|
|
|
return $_SESSION[$key];
|
|
|
|
}
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
2022-01-24 08:00:22 +00:00
|
|
|
public function set(string $key, $value): void
|
2022-01-23 21:56:36 +00:00
|
|
|
{
|
|
|
|
$_SESSION[$key] = $value;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function remove(string $key): void
|
|
|
|
{
|
|
|
|
if ($this->has($key))
|
|
|
|
{
|
|
|
|
unset($_SESSION[$key]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public function clear(): void
|
|
|
|
{
|
|
|
|
session_unset();
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: throwaway code; rewrite for readability and also implement proper flashing by removing messages after one request
|
|
|
|
public function flash(string $msg, string $type = 'info'): void
|
|
|
|
{
|
2022-01-26 19:28:00 +00:00
|
|
|
$types = [
|
|
|
|
"info",
|
|
|
|
"success",
|
|
|
|
"danger",
|
|
|
|
"warning"
|
|
|
|
];
|
|
|
|
if (!in_array($type, $types)) {
|
|
|
|
throw new Exception("Flash type: \"$type\" does not exist");
|
|
|
|
}
|
2022-01-23 21:56:36 +00:00
|
|
|
$key = 'flashed_messages';
|
2022-01-24 11:55:37 +00:00
|
|
|
if (!$this->has($key))
|
|
|
|
{
|
2022-01-23 21:56:36 +00:00
|
|
|
$this->set($key, []);
|
|
|
|
}
|
2022-01-24 11:55:37 +00:00
|
|
|
if (count($this->get($key)) >= 100)
|
|
|
|
{
|
2022-01-23 21:56:36 +00:00
|
|
|
$this->remove($key);
|
|
|
|
throw new Exception('Too many flashed messages!');
|
|
|
|
}
|
|
|
|
$msgs = $this->get($key);
|
|
|
|
$msgs[] = [
|
|
|
|
"message" => htmlspecialchars($msg),
|
|
|
|
"type" => $type
|
|
|
|
];
|
|
|
|
$this->set(
|
|
|
|
$key,
|
|
|
|
$msgs
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getFlashedMessages(): ?array
|
|
|
|
{
|
|
|
|
$key = 'flashed_messages';
|
2022-01-24 11:55:37 +00:00
|
|
|
if ($this->has($key))
|
|
|
|
{
|
2022-01-23 21:56:36 +00:00
|
|
|
$msgs = $this->get($key);
|
|
|
|
$this->remove($key);
|
|
|
|
return $msgs;
|
|
|
|
}
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
// END TODO;
|
2022-01-15 10:26:02 +00:00
|
|
|
}
|