This repository has been archived on 2023-01-06. You can view files and clone it, but cannot push or open issues or pull requests.
web/app/lib/App/Core/Session.php

99 lines
2.1 KiB
PHP
Raw Normal View History

2022-01-15 10:26:02 +00:00
<?php
2022-03-02 06:15:12 +00:00
namespace App\Core;
use \Exception;
2022-03-07 06:13:17 +00:00
use \InvalidArgumentException;
2022-03-02 06:15:12 +00:00
/**
* Handles anything to do with sessions
*/
2022-01-15 10:26:02 +00:00
class Session
{
public function __construct()
{
2022-03-03 04:11:14 +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-04-14 20:59:42 +00:00
public function get(string $key): mixed
2022-01-23 21:56:36 +00:00
{
if ($this->has($key))
{
return $_SESSION[$key];
}
return NULL;
}
2022-04-14 20:59:42 +00:00
public function set(string $key, mixed $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
2022-02-15 11:26:15 +00:00
public function flash(string $msg, string $type = 'info', bool $unsafe = FALSE): void
2022-01-23 21:56:36 +00:00
{
2022-01-26 19:28:00 +00:00
$types = [
"info",
"success",
"danger",
"warning"
];
if (!in_array($type, $types)) {
2022-03-07 06:13:17 +00:00
throw new InvalidArgumentException("Flash type: \"$type\" does not exist");
2022-01-26 19:28:00 +00:00
}
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[] = [
2022-02-15 11:26:15 +00:00
"message" => ($unsafe) ? $msg : htmlspecialchars($msg),
2022-01-23 21:56:36 +00:00
"type" => $type
];
$this->set(
$key,
$msgs
);
}
2022-02-23 15:45:12 +00:00
public function getFlashedMessages(): array
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
$msgs = $this->get($key);
$this->remove($key);
return $msgs;
}
2022-02-23 15:45:12 +00:00
return [];
2022-01-23 21:56:36 +00:00
}
// END TODO;
2022-01-15 10:26:02 +00:00
}