84 lines
2.2 KiB
PHP
84 lines
2.2 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Framework\Http\Session;
|
|
|
|
/**
|
|
* The FlashBag class provides a mechanism to manage flash messages in a session,
|
|
* typically used for temporary notifications such as success messages, error alerts,
|
|
* or other transient data between requests.
|
|
*/
|
|
final class FlashBag
|
|
{
|
|
private array $newFlashData = [];
|
|
|
|
public function __construct(
|
|
private Session $session
|
|
){
|
|
$this->session = $session;
|
|
|
|
// Sicherstellen, dass Flash-Bereich existiert
|
|
if (!$this->session->has(SessionKey::FLASH->value)) {
|
|
$this->session->set(SessionKey::FLASH->value, []);
|
|
}
|
|
}
|
|
|
|
public function add(string $type, string $message): void
|
|
{
|
|
$flashData = $this->session->get(SessionKey::FLASH->value, []);
|
|
|
|
if (!isset($flashData[$type])) {
|
|
$flashData[$type] = [];
|
|
}
|
|
|
|
$flashData[$type][] = $message;
|
|
$this->session->set(SessionKey::FLASH->value, $flashData);
|
|
}
|
|
|
|
public function get(string $type): array
|
|
{
|
|
$flashData = $this->session->get(SessionKey::FLASH->value, []);
|
|
$messages = $flashData[$type] ?? [];
|
|
|
|
// Nur für diesen spezifischen Typ löschen
|
|
if (isset($flashData[$type])) {
|
|
unset($flashData[$type]);
|
|
$this->session->set(SessionKey::FLASH->value, $flashData);
|
|
}
|
|
|
|
return $messages;
|
|
}
|
|
|
|
public function has(string $type): bool
|
|
{
|
|
$flashData = $this->session->get(SessionKey::FLASH->value, []);
|
|
return !empty($flashData[$type]);
|
|
}
|
|
|
|
public function all(): array
|
|
{
|
|
$flashData = $this->session->get(SessionKey::FLASH->value, []);
|
|
$this->session->set(SessionKey::FLASH->value, []);
|
|
|
|
return $flashData;
|
|
}
|
|
|
|
public function keep(string $type): void
|
|
{
|
|
if ($this->has($type)) {
|
|
$this->newFlashData[$type] = $this->session->get(SessionKey::FLASH->value)[$type];
|
|
}
|
|
}
|
|
|
|
public function keepAll(): void
|
|
{
|
|
$this->newFlashData = $this->session->get(SessionKey::FLASH->value, []);
|
|
}
|
|
|
|
public function age(): void
|
|
{
|
|
$this->session->set(SessionKey::FLASH->value, $this->newFlashData);
|
|
$this->newFlashData = [];
|
|
}
|
|
}
|