$1";
const REPLACE_ITALIC = "$1";
const REPLACE_UNDERLINE = "$1";
private bool $in_p = false;
private array $content = [];
private array $p = [];
public function parse(string $file_path): Article
{
$article = new Article();
$article->date = preg_replace(self::PATTERN_DATE, self::REPLACE_DATE, $file_path);
$article->ref = preg_replace(self::PATTERN_DATE, self::REPLACE_REF, $file_path);
$lines = file($file_path, FILE_IGNORE_NEW_LINES);
foreach ($lines as $line) {
if (substr($line, 0, 2) === "# ") {
$article->title = substr($line, 2);
continue;
}
if (substr($line, 0, 3) === "## ") {
$this->closeParagraph();
$this->content[] = "
" . substr($line, 3) . "
";
continue;
}
if (substr($line, 0, 4) === "### ") {
$this->closeParagraph();
$this->content[] = "" . substr($line, 4) . "
";
continue;
}
if (substr($line, 0, 5) === "#### ") {
$this->closeParagraph();
$this->content[] = "" . substr($line, 5) . "
";
continue;
}
if (preg_match(self::PATTERN_TAGS, $line, $matches)) {
$article->tags = explode(",", $matches[1]);
continue;
}
if (preg_match(self::PATTERN_IMG, $line, $matches)) {
$this->closeParagraph();
$this->content[] = "";
continue;
}
if ($line === "") {
$this->closeParagraph();
continue;
} else {
if (!$this->in_p) {
$this->content[] = "";
$this->in_p = true;
}
$this->p[] = $this->parseLine($line);
}
}
$this->closeParagraph();
array_unshift($this->content,
"",
" " . $article->title . "
",
" ",
""
);
$this->content[] = "";
$view_path = "./data/cache/{$article->date}_{$article->ref}.phtml";
file_put_contents($view_path, " " . implode("\n ", $this->content) . "\n");
$article->view = $view_path;
$this->content = [];
return $article;
}
private function closeParagraph()
{
if ($this->in_p) {
$this->content[] = " " . implode("
", $this->p);
$this->content[] = "
";
$this->in_p = false;
$this->p = [];
}
}
private function parseLine(string $line): string
{
$patterns = [
self::PATTERN_BOLD,
self::PATTERN_ITALIC,
self::PATTERN_UNDERLINE
];
$replacements = [
self::REPLACE_BOLD,
self::REPLACE_ITALIC,
self::REPLACE_UNDERLINE
];
return preg_replace($patterns, $replacements, htmlspecialchars($line, ENT_HTML5, UTF-8));
}
private function getHtmlTags(array $tags): string
{
$html = "";
foreach ($tags as $tag) {
$html .= "$tag";
}
return $html;
}
}