word-salad/database/factories/ArticleFactory.php

91 lines
2.4 KiB
PHP

<?php
namespace Database\Factories;
use App\Models\Author;
use App\Models\Article;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Article>
*/
class ArticleFactory extends Factory
{
/**
* Configure the model factory.
*/
public function configure(): static
{
return $this->afterMaking(function (Article $article) {
$article->convertMarkdownToMarkup();
})->afterCreating(function (Article $article) {
// ...
});
}
/**
* The current User being used by the factory.
*/
protected static Author $author;
/**
* The current Markdown body being used by the factory.
*/
protected static string $markdown_body;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'title' => fake()->words(3, true),
'slug' => fake()->unique()->slug(),
'author_id' => static::$author->id ??= Author::factory()->create()->id,
'subtitle' => fake()->sentence(),
'body' => '', // We'll update it after making using the on-Model method
'published_at' => fake()->date('Y-m-d H:m:s', now()->addDays(rand(0,20))),
'header_image_url' => fake()->imageUrl(),
'markdown_body' => $this->generateMarkdown(),
'processed_at' => fake()->date('Y-m-d H:m:s'),
];
}
/**
* Indicate the model's associated Author
*/
public function author(int|Author $author): static
{
if(is_int($author)) {
$author = Author::findOrFail($author);
}
static::$author = $author;
return $this->state(fn (array $attributes) => [
'author_id' => $author->id,
]);
}
private function generateMarkdown()
{
$markdown_result = '';
foreach(range(1,rand(15,45)) as $index) {
$dice_roll = rand(0,100);
if($dice_roll <= 50) { // Make a SubTitle
$markdown_result .= '## ' . fake()->words(rand(1,5), true) . "\n";
} elseif ($dice_roll <= 100) { // Make a paragraph
$markdown_result .= fake()->sentences(rand(2,5), true) . "\n";
}
// Always append a new line
$markdown_result .= "\n";
}
return $markdown_result;
}
}