Skip to content

Instantly share code, notes, and snippets.

@buchin
Created May 24, 2022 04:21
Show Gist options
  • Save buchin/ef172f70519d3404549a68d276826ddd to your computer and use it in GitHub Desktop.
Save buchin/ef172f70519d3404549a68d276826ddd to your computer and use it in GitHub Desktop.
<?php
namespace App;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $guarded = [];
protected $casts = [
"published_at" => "datetime",
"tags" => "array",
];
const TEMPLATES = [
"category",
"title",
"json_ld",
"content",
"markdown",
"tags",
];
public static function regenerate(Keyword $keyword): Post
{
$post = Post::firstOrCreate([
"keyword_id" => $keyword->id,
]);
$post = $post->setPublicationDate();
foreach (self::TEMPLATES as $template) {
$post = self::generate($template, $post);
$post = self::spin($template, $post);
}
$post->slug = str(
$post->id . "-" . htmlspecialchars_decode($post->keyword->name)
)->slug("-", config("shuriken.language"));
$post->category = config("export.category");
$post->save();
return $post;
}
public static function spin($template, $post)
{
$post->{$template} = Helper::spintax($post->{$template});
return $post;
}
public function setPublicationDate()
{
if (is_string(config("export.start"))) {
config([
"export.start" => Carbon::createFromFormat(
"Y-m-d",
config("export.start")
),
]);
}
if (is_string(config("export.end"))) {
config([
"export.end" => Carbon::createFromFormat(
"Y-m-d",
config("export.end")
),
]);
}
$start = config("export.start")->timestamp;
$end = config("export.end")->timestamp;
$date = Carbon::createFromTimestamp(rand($start, $end));
$this->published_at = $date;
return $this;
}
public static function generate(string $template, Post $post)
{
if ($template === "tags") {
$tags = [];
foreach ($post->keyword->related_keywords as $related_keyword) {
$tags[] = trim(
view("tags", ["keyword" => $related_keyword])->render()
);
}
$post->tags = $tags;
return $post;
}
$content = view($template, [
"post" => $post,
"keyword" => $post->keyword,
"images" => $post->keyword->images,
])->render();
$post->{$template} = trim($content);
return $post;
}
public function keyword()
{
return $this->belongsTo(Keyword::class);
}
public function getPreviousAttribute()
{
return Post::where("id", "<", $this->id)
->orderBy("id", "desc")
->first();
}
public function getParentAttribute()
{
$parent_keyword = $this->keyword->parent;
if (is_null($parent_keyword)) {
return null;
}
return Post::where("keyword_id", $parent_keyword->id)->first();
}
public function getNextAttribute()
{
return Post::where("id", ">", $this->id)
->orderBy("id", "asc")
->whereNotNull("content")
->first();
}
public function getRelatedAttribute()
{
return Post::where("keyword_id", $this->keyword->id)->get();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment