fn_b/app/Console/Commands/SetupNewsCategory.php

57 lines
2.7 KiB
PHP

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
final class SetupNewsCategory extends Command
{
protected $signature = 'news:setup {--apply : Create the news category}';
protected $description = 'Create the 看看资讯 top-level category without changing existing content';
public function handle(): int
{
$existing = DB::table('categories')->where('sSlug', 'news')->orWhere('sName', '看看资讯')->get();
if ($existing->isNotEmpty()) {
if ($existing->count() !== 1 || $existing[0]->sSlug !== 'news'
|| $existing[0]->sName !== '看看资讯' || (int) $existing[0]->iParentId !== 0 || (int) $existing[0]->iStatus !== 1) {
$this->error('Conflicting news category; inspect before changing it.');
return self::FAILURE;
}
$this->info('看看资讯 already exists at /news (id '.$existing[0]->id.').');
return self::SUCCESS;
}
$this->line('Create 看看资讯 at /news, after existing top-level categories.');
if (! $this->option('apply')) return self::SUCCESS;
$directory = storage_path('app/private/category-backups');
if (! is_dir($directory)) mkdir($directory, 0700, true);
$backup = $directory.'/news-'.Str::uuid().'.json';
$before = DB::table('categories')->orderBy('id')->get();
if (file_put_contents($backup, json_encode($before, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) === false) {
throw new \RuntimeException('Category backup failed.');
}
chmod($backup, 0600);
$id = DB::transaction(function () {
$rows = DB::table('categories')->lockForUpdate()->get();
if ($rows->contains(fn ($row) => $row->sSlug === 'news' || $row->sName === '看看资讯')) {
throw new \RuntimeException('Category state changed; rerun after inspection.');
}
return DB::table('categories')->insertGetId([
'iParentId' => 0, 'sName' => '看看资讯', 'sSlug' => 'news',
'sDescription' => '最新资讯与动态。',
'iSort' => $rows->where('iParentId', 0)->max('iSort') + 1,
'iStatus' => 1, 'sHtmlClass' => 'fas fa-newspaper',
'iShowChildren' => 0, 'aBanner' => null, 'aOpt' => null,
]);
});
Cache::forget('global_nav_tree');
\Spatie\ResponseCache\Facades\ResponseCache::clear();
$this->info('Created 看看资讯 at /news (id '.$id.'). Backup: '.$backup);
return self::SUCCESS;
}
}