AAAHHH IMMM.. IIIIM COOOMMMIIIIIIITIING!!!!!

This commit is contained in:
William 2023-02-03 13:57:08 +01:00
parent 5787e5c904
commit cbecf6d734
3 changed files with 70 additions and 38 deletions

View File

@ -2,28 +2,10 @@
namespace App\Controller;
use App\Config;
ChatController::init();
use App\Model\ChatModel;
abstract class ChatController
{
private static array $messages;
static function init()
{
if (!file_exists(Config::get('path_to_chat_json_file'))) {
file_put_contents(
Config::get('path_to_chat_json_file'),
json_encode([])
);
}
self::$messages = json_decode(
file_get_contents(Config::get('path_to_chat_json_file')),
true
);
}
static function index()
{
if (empty($_POST)) {
@ -36,7 +18,7 @@ abstract class ChatController
$nick = filter_input(INPUT_POST, 'nick');
$text = filter_input(INPUT_POST, 'text');
$errmsg = (function() use (&$text, &$nick): string|false {
$errmsg = (function() use (&$text, &$nick): string {
if (empty(trim($nick, ' '))) {
return 'You must choose a nickname.';
}
@ -55,26 +37,16 @@ abstract class ChatController
return 'Message body cannot be empty.';
}
return false;
return '';
})();
if (!$errmsg) {
if (count(self::$messages) > 100) {
array_pop(self::$messages);
}
array_unshift(self::$messages, [
'nick' => $nick,
'date' => time(),
'text' => $text
]);
file_put_contents(Config::get('path_to_chat_json_file'),
json_encode(
self::$messages
)
if (empty($errmsg)) {
ChatModel::save_message(
$nick,
$text
);
}
view('pages/chat/index', [
'nick' => $nick,
'just_sent_message' => true,
@ -84,11 +56,14 @@ abstract class ChatController
static function messages()
{
view('pages/chat/messages', ['messages' => self::$messages]);
view('pages/chat/messages',
['messages' => ChatModel::get_messages()]);
}
static function sync()
{
json_response(hash('crc32', serialize(self::$messages)));
json_response(hash('crc32', serialize(
ChatModel::get_messages()
)));
}
}

View File

@ -0,0 +1,50 @@
<?php
namespace App\Model;
use App\Config;
ChatModel::init();
abstract class ChatModel
{
private static array $messages;
static function init()
{
if (!file_exists(Config::get('path_to_chat_json_file'))) {
file_put_contents(
Config::get('path_to_chat_json_file'),
json_encode([])
);
}
self::$messages = json_decode(
file_get_contents(Config::get('path_to_chat_json_file')),
true
);
}
static function get_messages(): array
{
return self::$messages;
}
static function save_message(string $nick, string $text)
{
if (count(self::$messages) > 100) {
array_pop($messages);
}
array_unshift(self::$messages, [
'nick' => $nick,
'date' => time(),
'text' => $text
]);
file_put_contents(Config::get('path_to_chat_json_file'),
json_encode(
self::$messages
)
);
}
}

View File

@ -35,5 +35,12 @@ App::group('/chat', function() {
ChatController::sync(...));
});
App::group('/blog', function() {
App::get('/',
fn() => view('pages/blog/home'));
App::get('/test',
fn() => view('pages/blog/test'));
});
http_response_code(404);
view('errors/404');