2022-11-29 19:58:44 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
|
|
namespace App\Services;
|
|
|
|
|
|
|
|
|
|
use App\Models\Article;
|
|
|
|
|
|
2025-04-27 16:38:25 +01:00
|
|
|
class ArticleService
|
2022-11-29 19:58:44 +00:00
|
|
|
{
|
2026-09-19 17:16:11 +01:00
|
|
|
/**
|
|
|
|
|
* @throws \InvalidArgumentException if a published article already has this title
|
|
|
|
|
*/
|
2025-04-27 16:38:25 +01:00
|
|
|
public function create(array $data): Article
|
2022-11-29 19:58:44 +00:00
|
|
|
{
|
2026-09-19 17:16:11 +01:00
|
|
|
$attributes = [
|
2025-04-27 16:38:25 +01:00
|
|
|
'title' => $data['name'],
|
|
|
|
|
'main' => $data['content'],
|
2026-08-22 17:16:55 +01:00
|
|
|
'published' => ($data['post-status'] ?? null) !== 'draft',
|
2026-09-19 17:16:11 +01:00
|
|
|
];
|
|
|
|
|
|
|
|
|
|
$existing = Article::where('title', $data['name'])->first();
|
|
|
|
|
|
|
|
|
|
if ($existing !== null) {
|
|
|
|
|
if ($existing->published) {
|
|
|
|
|
throw new \InvalidArgumentException("An article titled \"{$data['name']}\" has already been published");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$existing->update($attributes);
|
|
|
|
|
|
|
|
|
|
return $existing;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return Article::create($attributes);
|
2022-11-29 19:58:44 +00:00
|
|
|
}
|
|
|
|
|
}
|