1
0
cms11/app/Classes/MarkdownManager.php

121 lines
2.4 KiB
PHP

<?php
namespace App\Classes;
use App\Services\Markdown\Formatter;
use App\Services\Markdown\Linter;
use Illuminate\Filesystem\FilesystemAdapter;
class MarkdownManager
{
/**
* Original markdown content
*/
private ?string $originalContent = null;
private FilesystemAdapter $disk;
private bool $isLoaded = false;
/**
* Current markdown content
*/
private ?string $content = null;
public function __construct(
protected string $filename,
protected Bundle $bundle
) {
$this->disk = $bundle->getDisk();
}
/**
* Return a boolean value indicating if the file actually exists on disk
*/
public function exists()
{
return $this->disk->exists($this->filename);
}
/**
* Load markdown file
*/
public function load(bool $reload = false)
{
if (!$this->isLoaded || $reload) {
$content = $this->disk->get($this->filename);
$this->originalContent = $content;
$this->content = $content;
$this->isLoaded = true;
}
}
/**
* Return current markdown content
*/
public function get(): ?string
{
return $this->content;
}
/**
* Convert markdown to HTML
*/
public function render()
{
$content = $this->bundle->replaceAttachmentsInMarkdown($this->content ?? '');
$formatter = new Formatter($content, $this->bundle);
$result = $formatter->render();
return $result;
}
/**
* Set current markdown content
*/
public function set(?string $content = null): void
{
$this->content = $content;
}
/**
* Return a boolean value indicating if the file has changed since it was
* loaded
*/
public function isDirty(): bool
{
return $this->originalContent !== $this->content;
}
/**
* Lint markdown
*/
public function lint(): void
{
if (!empty($this->content)) {
$linter = new Linter($this->content);
$this->content = $linter->format();
$this->save();
}
}
/**
* Store file on disk
*/
public function save(): bool
{
if (!$this->isDirty()) {
return false;
}
$this->disk->put($this->filename, $this->content ?? '');
$this->originalContent = $this->content;
return true;
}
}