Skip to content

Commit

Permalink
338: general code improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
Atmos4 committed Dec 13, 2024
1 parent 1606206 commit 330a691
Show file tree
Hide file tree
Showing 14 changed files with 196 additions and 47 deletions.
14 changes: 14 additions & 0 deletions .vscode/php.code-snippets
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"PHP Template if": {
"scope": "php,html,plaintext",
"prefix": "pif",
"body": ["<?php if ($1): ?>", "\t$0", "<?php endif ?>"],
"description": "Log output to console"
},
"PHP Template foreach": {
"scope": "php,html,plaintext",
"prefix": "pfe",
"body": ["<?php foreach ($1 as $2): ?>", "\t$0", "<?php endforeach ?>"],
"description": "Log output to console"
}
}
25 changes: 2 additions & 23 deletions app/pages/dev/sqlite_db.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,46 +9,25 @@
$values = $v->text("values")->placeholder("Values");
$result = null;

$db_name = env("SQLITE_DB_NAME") ?? "db.sqlite";
try {
$pdo = new PDO('sqlite:.sqlite/' . $db_name);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}

if ($v->valid()) {
try {
$sql = $input->value;
$stmt = $pdo->prepare($sql);
$result = $stmt->execute($values->value ? explode(",", $values->value) : null);
$rows = $stmt->fetchAll();
$rows = em()->getConnection()->fetchAllAssociative($input->value, $values->value ? explode(",", $values->value) : []);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
}

page("SQLITE");

?>
<p>Connected to
<?= $db_name ?>
</p>
<form method="post">
<?= $v ?>
<?= $input ?>
<?= $values ?>
<button>Execute</button>
</form>
<?php if ($result !== null): ?>
<?php if ($input->value): ?>
<section>Query:
<?= $input->value ?>
</section>
<section>Result:
<?= $result ? "success" : "error" ?>
</section>

<section>
Data:
<pre><?= print_r($rows, true) ?></pre>
Expand Down
5 changes: 5 additions & 0 deletions app/services/ToastService.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,11 @@ static function warning(string $message)
{
return self::create($message, ToastLevel::Warning);
}

static function fromResult(Result $r)
{
return $r->success ? self::success($r->print()) : self::error($r->print());
}
}

enum ToastLevel: string
Expand Down
5 changes: 2 additions & 3 deletions app/template/layout.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,9 @@

<!-- Intro.js -->
<script src="/assets/js/intro.min.js"></script>
<script>function start_intro() { introJs().start() }</script>
</head>

<body hx-ext="head-support,loading-states" <?= has_session("user_id") ? 'hx-boost="true"' : "" ?>
<body hx-ext="head-support,loading-states" <?= has_session("user_id") || $page->_boost ? 'hx-boost="true"' : "" ?>
hx-indicator="#hx-indicator" hx-on:show-modal="document.getElementById(event.detail.modalId).showModal()">
<?php
if ($page->nav && has_session("user_id")) {
Expand All @@ -63,7 +62,7 @@
<div id="hx-indicator" aria-busy="true"></div>
<main class="container" <?= $page->no_padding ? "style=\"padding:0\"" : "" ?>>
<?php if ($page->help): ?>
<div class="help-button" onclick="start_intro()" id="help-button"><i class="fas fa-question"></i></div>
<div class="help-button" onclick="introJs().start()" id="help-button"><i class="fas fa-question"></i></div>
<?php endif ?>
<?php if ($page->controlled) {
echo ControlNotice();
Expand Down
5 changes: 0 additions & 5 deletions assets/css/event_view.css
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,6 @@ details summary:focus:not([role="button"]) {
flex-wrap: wrap;
}

sl-tab-group {
--indicator-color: var(--primary);
--sl-color-primary-600: var(--primary);
}

dt {
font-weight: bold;
}
Expand Down
6 changes: 6 additions & 0 deletions assets/css/main.css
Original file line number Diff line number Diff line change
Expand Up @@ -687,3 +687,9 @@ article.notice > header,
display: flex;
justify-content: end;
}

/* Shoelace */
sl-tab-group {
--indicator-color: var(--primary);
--sl-color-primary-600: var(--primary);
}
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@
],
"dev": [
"Composer\\Config::disableProcessTimeout",
"php -S localhost:8000 server.php"
"# Server listening at http://localhost:8000",
"@php -S 0.0.0.0:8000 server.php"
],
"seed": "php bin/seed",
"db:migrate": "@php bin/doctrine --no-interaction migrations:migrate",
Expand Down
31 changes: 31 additions & 0 deletions database/migrations_sqlite/Version20241212115826.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

namespace intranose\Migrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20241212115826 extends AbstractMigration
{
public function getDescription(): string
{
return 'clubs';
}

public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE TABLE orm_clubs (slug VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY(slug))');
}

public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('DROP TABLE orm_clubs');
}
}
29 changes: 29 additions & 0 deletions database/models/clubs.db.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\Table;

#[Entity, Table(name: 'clubs')]
class Club
{
#[Id, Column(unique: true)]
public string $slug; // intranose

#[Column]
public string $name; // Intranose

function __construct($name, $slug)
{
$this->name = $name;
$this->slug = $slug;
}

function toForm()
{
return [
"name" => $this->name,
"slug" => $this->slug,
];
}
}
8 changes: 6 additions & 2 deletions engine/core/Router.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
<?php
class Router extends Singleton
{

private array $dynamicSegments;
private int $level = 0;

Expand All @@ -10,7 +9,9 @@ private function render($path_to_include = "app/pages/404.php")
try {
$this->level = ob_get_level();
ob_start();
include_once $path_to_include;
if (!@include $path_to_include) {
throw new Error("Router: $path_to_include not found");
}
$page = Page::getInstance();
if ($page->title) {
$content = ob_get_clean();
Expand All @@ -28,6 +29,9 @@ private function render($path_to_include = "app/pages/404.php")
if (!get_header("hx-request") || get_header("hx-boosted")) {
Page::reset();
page("Erreur 500")->disableNav()->heading(false);
if (is_dev()) {
echo $e->getMessage();
}
}
$this->render("app/pages/500.php");
}
Expand Down
6 changes: 6 additions & 0 deletions engine/core/rendering/Page.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,18 @@ class Page extends SingletonDependency
public array $scripts = [];
public bool $no_padding = false;
public bool $help = false;
public bool $_boost = false;

public function css(string $css)
{
$this->css_files[] = "/assets/css/$css";
return $this;
}
public function boost(bool $b = true)
{
$this->_boost = $b;
return $this;
}
public function description(string $description)
{
$this->description = $description;
Expand Down
87 changes: 83 additions & 4 deletions engine/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -237,13 +237,15 @@ function format_date($date, string $format = null)
}
return formatter($format)->format($date);
}

/** CSRF Protection */
function set_csrf()
{
if (!isset($_SESSION["csrf"])) {
$_SESSION["csrf"] = bin2hex(random_bytes(50));
}
return '<input type="hidden" name="csrf" value="' . $_SESSION["csrf"] . '">';
return '<input type="hidden" name="csrf" value="' . gen_csrf() . '">';
}
function gen_csrf()
{
return $_SESSION["csrf"] ??= bin2hex(random_bytes(50));
}
function is_csrf_valid()
{
Expand All @@ -260,4 +262,81 @@ function is_csrf_valid()
function logger()
{
return MainLogger::get();
}

// --- nitty gritty

/** Same as `rm -rf` */
function rm_rf($path)
{
if (!is_dir($path)) {
return unlink($path);
}
$items = scandir($path);
foreach ($items as $item) {
if ($item === '.' || $item === '..') {
continue;
}
$itemPath = $path . DIRECTORY_SEPARATOR . $item;
if (is_dir($itemPath)) {
rm_rf($itemPath);
} else {
unlink($itemPath);
}
}
return rmdir($path);
}

/**
* Wrapper for success or failure of a procedure
*/
class Result
{
function __construct(public $success, public $data, public $message)
{
}

static function wrap($data = null, $msg = "")
{
return new static(true, $data, $msg);
}

static function ok($msg = "")
{
return new static(true, null, $msg);
}

/**
* Wraps a closure with try catch
* @param Closure(void):Result $f
* @return Result
*/
static function try(callable $f): Result
{
try {
return $f() ?? Result::ok();
} catch (Throwable $t) {
return Result::error($t->getMessage());
}
}

static function error($msg = "")
{
return new static(false, null, $msg);
}

function print()
{
return (string) $this->message;
}

function __tostring()
{
return $this->print();
}

function unwrap()
{
return $this->data;
}
}
11 changes: 10 additions & 1 deletion engine/validation/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,16 @@ function get_field(string $key): Field
return $this->fields[$key] ?? new Field($key);
}

function render_validation()
/**
* To be used with a standalone hx-post / hx-delete
* @return string
*/
function hx_action(): string
{
return "hx-vals='{\"action\":\"$this->action\",\"csrf\":\"" . gen_csrf() . "\"}'";
}

function render_validation(): string
{
$result = "";

Expand Down
8 changes: 0 additions & 8 deletions engine/validation/fields.php
Original file line number Diff line number Diff line change
Expand Up @@ -616,18 +616,10 @@ function set_type(): void
$this->type = FieldType::Password;
}

public bool $new = false;

function check(string|null $msg = null): void
{
}

function set_new(): static
{
$this->new = true;
return $this;
}

function secure(): static
{
return $this->with_lowercase()->with_uppercase()->with_number()->min_length(8);
Expand Down

0 comments on commit 330a691

Please sign in to comment.