feat: initial foundation for collaborative canteen ordering system in vanilla PHP
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Core;
|
||||
|
||||
class View
|
||||
{
|
||||
private static string $viewsPath = __DIR__ . '/../Views/';
|
||||
private static array $sections = [];
|
||||
private static ?string $currentSection = null;
|
||||
|
||||
public static function render(string $view, array $data = [], ?string $layout = 'layouts/main'): string
|
||||
{
|
||||
$viewFile = self::$viewsPath . str_replace('.', '/', $view) . '.php';
|
||||
|
||||
if (!file_exists($viewFile)) {
|
||||
throw new \RuntimeException("View file not found: {$viewFile}");
|
||||
}
|
||||
|
||||
// Extract variables for view scope
|
||||
extract($data);
|
||||
|
||||
// Capture view content
|
||||
ob_start();
|
||||
require $viewFile;
|
||||
$content = ob_get_clean();
|
||||
|
||||
// If a layout is specified, wrap content with the layout
|
||||
if ($layout !== null) {
|
||||
$layoutFile = self::$viewsPath . str_replace('.', '/', $layout) . '.php';
|
||||
if (!file_exists($layoutFile)) {
|
||||
throw new \RuntimeException("Layout file not found: {$layoutFile}");
|
||||
}
|
||||
|
||||
ob_start();
|
||||
require $layoutFile;
|
||||
return ob_get_clean();
|
||||
}
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
public static function setFlash(string $type, string $message): void
|
||||
{
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
session_start();
|
||||
}
|
||||
$_SESSION['flash'][$type][] = $message;
|
||||
}
|
||||
|
||||
public static function getFlashes(): array
|
||||
{
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
session_start();
|
||||
}
|
||||
$flashes = $_SESSION['flash'] ?? [];
|
||||
unset($_SESSION['flash']);
|
||||
return $flashes;
|
||||
}
|
||||
|
||||
public static function csrfToken(): string
|
||||
{
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
session_start();
|
||||
}
|
||||
if (empty($_SESSION['csrf_token'])) {
|
||||
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
|
||||
}
|
||||
return $_SESSION['csrf_token'];
|
||||
}
|
||||
|
||||
public static function csrfField(): string
|
||||
{
|
||||
$token = self::csrfToken();
|
||||
return '<input type="hidden" name="_csrf" value="' . htmlspecialchars($token, ENT_QUOTES, 'UTF-8') . '">';
|
||||
}
|
||||
|
||||
public static function escape(mixed $value): string
|
||||
{
|
||||
return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user