83 lines
2.4 KiB
PHP
83 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Jobs\Tasks;
|
|
|
|
use App\Helpers\FirstParty\OpenAI\OpenAI;
|
|
use App\Models\Author;
|
|
use App\Models\Post;
|
|
use App\Models\PostCategory;
|
|
use App\Models\SerpUrl;
|
|
use Exception;
|
|
|
|
class GenerateArticleTask
|
|
{
|
|
public static function handle(SerpUrl $serp_url)
|
|
{
|
|
|
|
$ai_titles = OpenAI::suggestArticleTitles($serp_url->title, $serp_url->description, 1);
|
|
|
|
if (is_null($ai_titles)) {
|
|
return self::saveAndReturnSerpProcessStatus($serp_url, -2);
|
|
}
|
|
|
|
$suggestion = null;
|
|
|
|
// dump($ai_titles);
|
|
|
|
try {
|
|
$random_key = array_rand($ai_titles?->suggestions, 1);
|
|
|
|
$suggestion = $ai_titles->suggestions[$random_key];
|
|
|
|
} catch (Exception $e) {
|
|
return self::saveAndReturnSerpProcessStatus($serp_url, -1);
|
|
}
|
|
|
|
if (is_null($suggestion)) {
|
|
return self::saveAndReturnSerpProcessStatus($serp_url, -3);
|
|
}
|
|
|
|
$markdown = OpenAI::writeArticle($suggestion->title, $suggestion->description, $suggestion->article_type, 500, 800);
|
|
|
|
if (is_empty($markdown)) {
|
|
return self::saveAndReturnSerpProcessStatus($serp_url, -4);
|
|
}
|
|
|
|
$post = new Post;
|
|
$post->title = $suggestion->title;
|
|
$post->type = $suggestion->article_type;
|
|
$post->short_title = $ai_titles->short_title;
|
|
$post->main_keyword = $ai_titles->main_keyword;
|
|
$post->keywords = $suggestion->photo_keywords;
|
|
$post->slug = str_slug($suggestion->title);
|
|
$post->excerpt = $suggestion->description;
|
|
$post->author_id = Author::find(1)->id;
|
|
$post->featured = false;
|
|
$post->featured_image = null;
|
|
$post->body = $markdown;
|
|
$post->status = 'draft';
|
|
|
|
if ($post->save()) {
|
|
$post_category = new PostCategory;
|
|
$post_category->post_id = $post->id;
|
|
$post_category->category_id = $serp_url->category->id;
|
|
|
|
if ($post_category->save()) {
|
|
return self::saveAndReturnSerpProcessStatus($serp_url, 1);
|
|
} else {
|
|
return self::saveAndReturnSerpProcessStatus($serp_url, -5);
|
|
}
|
|
}
|
|
|
|
return self::saveAndReturnSerpProcessStatus($serp_url, -6);
|
|
}
|
|
|
|
private static function saveAndReturnSerpProcessStatus($serp_url, $process_status)
|
|
{
|
|
$serp_url->process_status = $process_status;
|
|
$serp_url->save();
|
|
|
|
return $serp_url->process_status;
|
|
}
|
|
}
|