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/core/Session.php

84 lines
1.8 KiB
PHP
Raw Normal View History

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);
}
// 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;
}
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
{
$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
}