dragon_fire/www/mysql_adapter.php

110 lines
2.5 KiB
PHP
Raw Normal View History

<?php
use Spatie\YamlFrontMatter\YamlFrontMatter;
class MySQLAdapter {
public $raw;
function __construct() {
$this->raw = mysqli_connect('mysql', 'root', 'example', 'dragon_fire');
if (!$this->raw)
{
echo 'Connection failed<br>';
echo 'Error number: ' . mysqli_connect_errno() . '<br>';
echo 'Error message: ' . mysqli_connect_error() . '<br>';
die();
}
}
function _exec($qery, $argtypes, ...$args) {
$stmt = $this->raw->prepare($qery);
$stmt->bind_param($argtypes, ...$args);
$stmt->execute();
return $stmt->get_result();
}
function _prepare_post_data($post_data) {
if($post_data == null) {
$post_data = [
"found" => false
];
}
else {
$post_data["found"] = true;
$post_data["post_metadata"] = json_decode($post_data["post_metadata"]);
}
return $post_data;
}
function save_markdown_post($post_path, $post_data) {
$frontmatter_post = YamlFrontMatter::parse($post_data);
$post_path = chop($post_path, '/');
$path_depth = substr_count($post_path, "/");
$post_content = $frontmatter_post->body();
$post_metadata = $frontmatter_post->matter();
$post_metadata['type'] = 'text/markdown';
var_dump($post_path, $post_content, $post_metadata);
$qry = "
INSERT INTO posts
(post_path, post_path_depth, post_metadata, post_content)
VALUES
( ?, ?, ?, ?) AS new
ON DUPLICATE KEY UPDATE post_metadata=new.post_metadata, post_content=new.post_content;";
$this->_exec($qry, "siss",
$post_path,
$path_depth,
json_encode($post_metadata),
$post_content);
}
function get_post_by_path($post_path, $with_subposts = true) {
$qry = "SELECT * FROM posts WHERE post_path = ?";
$post_path = chop($post_path, '/');
$post_data = $this->_prepare_post_data($this->_exec($qry, "s", $post_path)->fetch_assoc());
if($with_subposts) {
$post_data['subposts'] = $this->get_subposts_by_path($post_path);
}
return $post_data;
}
function get_subposts_by_path($path) {
global $sql;
$path = chop($path, '/');
$path_depth = substr_count($path, "/");
$qry = "SELECT post_path, post_metadata
FROM posts
WHERE (post_path LIKE CONCAT(?,'/%'))
AND post_path_depth = ?
ORDER BY post_create_time DESC
LIMIT 10";
$post_data = $this->_exec($qry, "si", $path, $path_depth+1)->fetch_all(MYSQLI_ASSOC);
$fn = function($data) {
return $this->_prepare_post_data($data);
};
$post_data = array_map($fn, $post_data);
return $post_data;
}
}
?>