Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Restructure backend models #26

Merged
merged 7 commits into from
Mar 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/Actions/MarkdownConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@ public static function parse(string $markdown): string
if (Features::hasTorchlight()
&& config('torchlight.attribution.enabled', true)
&& str_contains($html, 'Syntax highlighted by torchlight.dev')) {
$html .= $converter->convert(config('torchlight.attribution.markdown', 'Syntax highlighted by torchlight.dev'));
$html .= $converter->convert(config(
'torchlight.attribution.markdown',
'Syntax highlighted by torchlight.dev'
));
}

return $html;
Expand Down
10 changes: 7 additions & 3 deletions src/Hyde.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,15 @@ public static function uriPath(?string $path = ''): string|false
* Serves as a static shorthand for \Hyde\Framework\Models\MarkdownPost::getCollection()
* @return \Illuminate\Support\Collection
* @throws \Exception
* @see MarkdownPost::getCollection
*
*/
public static function getLatestPosts(): Collection
{
return MarkdownPost::getCollection();
$collection = new Collection();

foreach (glob(Hyde::path('_posts/*.md')) as $filepath) {
$collection->push((new MarkdownPostParser(basename($filepath, '.md')))->get());
}

return $collection->sortByDesc('matter.date');
}
}
33 changes: 16 additions & 17 deletions src/MarkdownPageParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

namespace Hyde\Framework;

use Hyde\Framework\Services\MarkdownFileService;
use Hyde\Framework\Models\MarkdownPage;
use JetBrains\PhpStorm\ArrayShape;
use Illuminate\Support\Str;
use JetBrains\PhpStorm\NoReturn;
use JetBrains\PhpStorm\Pure;
use Exception;
Expand All @@ -16,31 +17,25 @@
class MarkdownPageParser
{
/**
* @var string the full path to the Markdown file
* The page title
* @var string
*/
private string $filepath;

public string $title;
/**
* The extracted page body
* @var string
*/
public string $body;

/**
* The page title
* @var string
*/
public string $title;

/**
* @param string $slug of the Markdown file (without extension)
* @throws Exception if the file cannot be found in _pages
* @example `new MarkdownPageParser('example-page')`
*/
public function __construct(protected string $slug)
{
$this->filepath = Hyde::path("_pages/$slug.md");
if (!file_exists($this->filepath)) {
if (!file_exists(Hyde::path("_pages/$slug.md"))) {
throw new Exception("File _pages/$slug.md not found.", 404);
}

Expand All @@ -54,12 +49,16 @@ public function __construct(protected string $slug)
#[NoReturn]
public function execute(): void
{
// Get the text stream from the markdown file
$stream = file_get_contents($this->filepath);
$document = (new MarkdownFileService(Hyde::path("_pages/$this->slug.md")))->get();

$this->title = $this->findTitleTag($stream) ?? Str::title(str_replace('-', ' ', $this->slug));
if (isset($document->matter['title'])) {
$this->title = $document->matter['title'];
} else {
$this->title = $this->findTitleTag($document->body) ??
Str::title(str_replace('-', ' ', $this->slug));
}

$this->body = $stream;
$this->body = $document->body;
}

/**
Expand All @@ -85,6 +84,6 @@ public function findTitleTag(string $stream): string|false
#[Pure]
public function get(): MarkdownPage
{
return new MarkdownPage($this->slug, $this->title, $this->body);
return new MarkdownPage([], $this->body, $this->slug, $this->title);
}
}
106 changes: 5 additions & 101 deletions src/MarkdownPostParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

namespace Hyde\Framework;

use Hyde\Framework\Services\MarkdownFileService;
use Hyde\Framework\Models\MarkdownPost;
use JetBrains\PhpStorm\ArrayShape;
use JetBrains\PhpStorm\NoReturn;
use JetBrains\PhpStorm\Pure;
use Exception;
Expand All @@ -15,11 +15,6 @@
*/
class MarkdownPostParser
{
/**
* @var string the full path to the Markdown file
*/
private string $filepath;

/**
* The extracted Front Matter
* @var array
Expand All @@ -39,8 +34,7 @@ class MarkdownPostParser
*/
public function __construct(protected string $slug)
{
$this->filepath = Hyde::path("_posts/$slug.md");
if (!file_exists($this->filepath)) {
if (!file_exists(Hyde::path("_posts/$slug.md"))) {
throw new Exception("File _posts/$slug.md not found.", 404);
}

Expand All @@ -55,103 +49,13 @@ public function __construct(protected string $slug)
public function execute(): void
{
// Get the text stream from the markdown file
$stream = file_get_contents($this->filepath);

// Split out the front matter and markdown
$split = $this->split($stream);
$document = (new MarkdownFileService(Hyde::path("_posts/$this->slug.md")))->get();

$this->matter = array_merge($this->parseFrontMatter($split['matter']), [
$this->matter = array_merge($document->matter, [
'slug' => $this->slug // Make sure to use the filename as the slug and not any potential override
]);

// Implode the line array back into a markdown string
$this->body = implode("\n", $split['markdown']);
}

/**
* Split the front matter from the markdown.
* @param string $stream
* @return array
*/
#[ArrayShape(['matter' => "array", 'markdown' => "array"])]
public function split(string $stream): array
{
$lines = explode("\n", $stream);

// Find the start and end position of the YAML block.
// Note that unless something is wrong with the file the start index should always be 0.
$matterSectionIndex = [];
foreach ($lines as $lineNumber => $lineContents) {
if (str_starts_with($lineContents, '---')) {
if (sizeof($matterSectionIndex) === 0) {
$matterSectionIndex['start'] = $lineNumber;
} elseif (sizeof($matterSectionIndex) === 1) {
$matterSectionIndex['end'] = $lineNumber;
break;
}
}
}

// Construct the new line arrays
$matter = [];
$markdown = [];
foreach ($lines as $lineNumber => $lineContents) {
if ($lineNumber <= $matterSectionIndex['end']) {
$matter[] = $lineContents;
} else {
$markdown[] = $lineContents;
}
}

// Remove the dashes
unset($matter[$matterSectionIndex['start']]);
unset($matter[$matterSectionIndex['end']]);

return [
'matter' => $matter,
'markdown' => $markdown,
];
}

/**
* Parse lines of Front Matter YAML into an associative array.
*
* @deprecated 0.6.0 - Please use the MarkdownFileService for preprocessing
*
* @param array $lines
* @return array
*/
public function parseFrontMatter(array $lines): array
{
$matter = [];
foreach ($lines as $line) {
if (!str_contains($line, ':')) {
continue; // The front matter is invalid, so we skip the line.
}

// Separate the key from the value
$array = (explode(': ', $line, 2));

// Assign the split values into variables, so it's easier to keep track of them.
$key = $array[0];
$value = $array[1];

// Filter the value to ensure a predictable state

// Remove quotes while allowing quotes within the actual text
if (str_starts_with($value, '"') && str_ends_with($value, '"')) {
$value = substr($value, 1);
$value = substr($value, 0, -1);
}

// Trim trailing whitespace
$value = trim($value, ' ');
// Trim trailing return character
$value = trim($value, "\r");

$matter[$key] = $value;
}
return $matter;
$this->body = $document->body;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Models/MarkdownDocument.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,4 @@ public function __construct(array $matter, string $body)
$this->matter = $matter;
$this->body = $body;
}
}
}
20 changes: 7 additions & 13 deletions src/Models/MarkdownPage.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,19 @@

namespace Hyde\Framework\Models;

use Hyde\Framework\Hyde;
use JetBrains\PhpStorm\Pure;

/**
* A simple class that contains the content of a basic Markdown Page.
* The basis for custom Markdown Pages.
*/
class MarkdownPage
class MarkdownPage extends MarkdownDocument
{
/**
* The Page Title
* @var string
*/
public string $title;

/**
* The Markdown Content
* @var string
*/
public string $content;

/**
* The Post Slug
* @var string
Expand All @@ -31,14 +24,15 @@ class MarkdownPage
/**
* Construct the object.
*
* @param array $matter
* @param string $body
* @param string $slug
* @param string $title
* @param string $content
*/
public function __construct(string $slug, string $title, string $content)
#[Pure] public function __construct(array $matter, string $body, string $slug, string $title)
{
$this->slug = $slug;
parent::__construct($matter, $body);
$this->title = $title;
$this->content = $content;
$this->slug = $slug;
}
}
43 changes: 6 additions & 37 deletions src/Models/MarkdownPost.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,15 @@

namespace Hyde\Framework\Models;

use Hyde\Framework\Hyde;
use Hyde\Framework\MarkdownPostParser;
use Illuminate\Support\Collection;
use JetBrains\PhpStorm\Pure;

/**
* A simple class that contains the Front Matter and Markdown text of a post.
* The basis for Markdown Blog Posts.
*/
class MarkdownPost
class MarkdownPost extends MarkdownDocument
{
/**
* The Front Matter
* @var array
*/
public array $matter;

/**
* The Markdown body
* @var string
*/
public string $body;

/**
* The Post slug
* The Post Slug
* @var string
*/
public string $slug;
Expand All @@ -36,26 +22,9 @@ class MarkdownPost
* @param string $body
* @param string $slug
*/
public function __construct(array $matter, string $body, string $slug)
#[Pure] public function __construct(array $matter, string $body, string $slug)
{
$this->matter = $matter;
$this->body = $body;
parent::__construct($matter, $body);
$this->slug = $slug;
}

/**
* Get a Laravel Collection of all Posts as MarkdownPost objects.
* @return Collection
* @throws \Exception
*/
public static function getCollection(): Collection
{
$collection = new Collection();

foreach (glob(Hyde::path('_posts/*.md')) as $filepath) {
$collection->push((new MarkdownPostParser(basename($filepath, '.md')))->get());
}

return $collection->sortByDesc('matter.date');
}
}
2 changes: 1 addition & 1 deletion src/Services/MarkdownFileService.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,4 @@ public function get(): MarkdownDocument
{
return new MarkdownDocument($this->matter, $this->body);
}
}
}
2 changes: 1 addition & 1 deletion src/StaticPageBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ private function compilePage(): string
{
return view('hyde::layouts/page')->with([
'title' => $this->page->title,
'markdown' => MarkdownConverter::parse($this->page->content),
'markdown' => MarkdownConverter::parse($this->page->body),
'currentPage' => $this->page->slug
])->render();
}
Expand Down
5 changes: 1 addition & 4 deletions tests/stubs/_pages/markdown.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
---
title: Markdown Page Example
---
# Markdown Page Example

## This Markdown file will be turned into a simple static HTML page