Skip to content

Commit

Permalink
Add trait to handle Authors in the data layer
Browse files Browse the repository at this point in the history
  • Loading branch information
caendesilva committed Apr 19, 2022
1 parent d463d61 commit 62f3793
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/Models/HasAuthor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

namespace Hyde\Framework\Models;

use Hyde\Framework\Services\AuthorService;

/**
* Trait HasAuthor
*
* @see \Tests\Unit\HasAuthorTest
*/
trait HasAuthor
{
public Author $author;

public function constructAuthor(): void
{
if (isset($this->matter['author'])) {
if (is_string($this->matter['author'])) {
$this->author = $this->findAuthor($this->matter['author']);
}
if (is_array($this->matter['author'])) {
$this->author = $this->createAuthor($this->matter['author']);
}
}
}

protected function findAuthor(string $author): Author
{
return AuthorService::find($author) ?: new Author($author);
}

protected function createAuthor(array $data): Author
{
$username = $data['username'] ?? $data['name'] ?? 'Guest';
return new Author($username, $data);
}
}
2 changes: 2 additions & 0 deletions src/Models/MarkdownPost.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

class MarkdownPost extends MarkdownDocument
{
use HasAuthor;
use HasMetadata;
use HasDateString;
use HasFeaturedImage;
Expand All @@ -17,6 +18,7 @@ public function __construct(array $matter, string $body, string $title = '', str
{
parent::__construct($matter, $body, $title, $slug);

$this->constructAuthor();
$this->constructMetadata();
$this->constructDateString();
$this->constructFeaturedImage();
Expand Down

0 comments on commit 62f3793

Please sign in to comment.