You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/AnnouncementService.php

200 lines
8.5 KiB
PHTML

<?php
namespace App\Services;
use App\Models\Ann;
use App\Services\Cloud\CloudError;
/** Plain-text publication; only explicit status actions publish existing records. */
final class AnnouncementService
{
private const TYPES = ['notice' => '通知', 'maintenance' => '维护', 'incident' => '故障'];
private const COLUMNS = ['id', 'title', 'type', 'body', 'status', 'published_at', 'updated_at'];
public static function page(array $actor, array $input = []): array
{
self::authorize($actor);
$filters = self::filters($input, true);
$query = Ann::query();
if ($filters['type'] !== 'all') {
$query->where('type', $filters['type']);
}
if ($filters['status'] !== 'all') {
$query->where('status', $filters['status']);
}
if ($filters['q'] !== '') {
$pattern = '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $filters['q']) . '%';
$query->where(static function ($query) use ($pattern): void {
$query->whereRaw("title LIKE ? ESCAPE '!'", [$pattern])
->orWhereRaw("body LIKE ? ESCAPE '!'", [$pattern]);
});
}
return self::listing($query, $filters) + ['filters' => $filters];
}
public static function published(array $actor, array $input = []): array
{
self::authorize($actor, false, false);
$filters = self::filters($input, false);
return self::listing(Ann::query()->where('status', 'published'), $filters);
}
public static function detail(array $actor, string $id): array
{
self::authorize($actor);
return self::dto(self::find($id));
}
public static function save(array $actor, array $input, ?string $id = null): array
{
self::authorize($actor, true);
$values = self::validate($input);
return (new Ann())->getConnection()->transaction(static function () use ($id, $values): array {
$ann = $id === null ? new Ann() : self::find($id, true);
$now = date('Y-m-d H:i:s');
if ($id === null) {
$ann->published_at = null;
} else {
// A stale editor must not republish an announcement withdrawn by
// another administrator. Existing status changes are explicit.
$values['status'] = (string) $ann->status;
}
if ($values['status'] === 'published' && ($id === null || $ann->status !== 'published')) {
$ann->published_at = $now;
}
foreach ($values as $field => $value) {
$ann->$field = $value;
}
$ann->updated_at = $now;
$ann->save();
return self::dto($ann);
});
}
public static function setStatus(array $actor, string $id, array $input): array
{
self::authorize($actor, true);
$status = self::choice($input, 'status', ['published', 'withdrawn']);
return (new Ann())->getConnection()->transaction(static function () use ($id, $status): array {
$ann = self::find($id, true);
if ($ann->status !== $status) {
if ($status === 'published' && (trim((string) $ann->title) === '' || trim((string) $ann->body) === '')) {
throw new CloudError('请先填写公告标题和正文', 400);
}
$ann->status = $status;
$ann->updated_at = date('Y-m-d H:i:s');
if ($status === 'published') {
$ann->published_at = $ann->updated_at;
}
$ann->save();
}
return self::dto($ann);
});
}
public static function authorize(array $actor, bool $write = false, bool $admin = true): void
{
if ((int) ($actor['user_id'] ?? 0) < 1) {
throw new CloudError('请先登录', 401);
}
if (($admin && !($actor['is_admin'] ?? false))
|| ($write && (!($actor['is_super_admin'] ?? false) || !($actor['can_manage'] ?? false)))) {
throw new CloudError($write ? '只有超级管理员可以管理公告' : '需要管理员权限', 403);
}
}
private static function listing($query, array &$filters): array
{
$total = (clone $query)->count();
$totalPages = max(1, (int) ceil($total / $filters['per_page']));
$filters['page'] = min($filters['page'], $totalPages);
$items = $query->orderByDesc('published_at')->orderByDesc('id')
->offset(($filters['page'] - 1) * $filters['per_page'])->limit($filters['per_page'])
->get(self::COLUMNS)->map(static fn ($row): array => self::dto($row))->all();
return ['items' => $items, 'pagination' => ['page' => $filters['page'], 'per_page' => $filters['per_page'],
'total' => $total, 'total_pages' => $totalPages], 'generated_at' => time()];
}
private static function filters(array $input, bool $admin): array
{
$page = self::integer($input['page'] ?? 1, '页码', 1, 1000000);
$perPage = self::integer($input['per_page'] ?? ($admin ? 20 : 10), '每页条数', 1, 100);
if (!in_array($perPage, $admin ? [20, 50, 100] : [10, 20, 50], true)) {
throw new CloudError('每页条数不受支持', 400);
}
if (!$admin) {
return ['page' => $page, 'per_page' => $perPage];
}
return ['q' => self::text($input['q'] ?? '', '关键词', 80, false),
'type' => self::choice($input, 'type', ['all', 'notice', 'maintenance', 'incident'], 'all'),
'status' => self::choice($input, 'status', ['all', 'published', 'withdrawn'], 'all'),
'page' => $page, 'per_page' => $perPage];
}
private static function validate(array $input): array
{
return ['title' => self::text($input['title'] ?? null, '标题', 120),
'type' => self::choice($input, 'type', array_keys(self::TYPES)),
'body' => self::text($input['body'] ?? null, '正文', 20000),
'status' => self::choice($input, 'status', ['published', 'withdrawn'])];
}
private static function text($value, string $label, int $limit, bool $required = true): string
{
if (!is_string($value) || !mb_check_encoding($value, 'UTF-8')
|| preg_match('/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/', $value)) {
throw new CloudError($label . '格式不正确', 400);
}
$value = trim(str_replace(["\r\n", "\r"], "\n", $value));
if (($required && $value === '') || mb_strlen($value, 'UTF-8') > $limit
|| ($label === '标题' && str_contains($value, "\n"))) {
throw new CloudError($label . '不能为空且最多 ' . $limit . ' 个字符', 400);
}
return $value;
}
private static function choice(array $input, string $key, array $allowed, ?string $default = null): string
{
$value = $input[$key] ?? $default;
if (!is_string($value) || !in_array($value, $allowed, true)) {
throw new CloudError('公告' . ($key === 'type' ? '类型' : '状态') . '不正确', 400);
}
return $value;
}
private static function integer($value, string $label, int $min, int $max): int
{
if ((!is_int($value) && !is_string($value)) || !preg_match('/^[0-9]+$/D', (string) $value)
|| strlen((string) $value) > 9 || (int) $value < $min || (int) $value > $max) {
throw new CloudError($label . '不正确', 400);
}
return (int) $value;
}
private static function find(string $id, bool $lock = false): Ann
{
if (!preg_match('/^[1-9][0-9]{0,9}$/D', $id) || (int) $id > 2147483647) {
throw new CloudError('公告编号不正确', 400);
}
$query = Ann::query()->where('id', $id);
if ($lock) {
$query->lockForUpdate();
}
$ann = $query->first(self::COLUMNS);
if ($ann === null) {
throw new CloudError('公告不存在', 404);
}
return $ann;
}
private static function dto(Ann $ann): array
{
$type = (string) $ann->type;
return ['id' => (string) $ann->id, 'title' => (string) $ann->title,
'type' => $type, 'type_label' => self::TYPES[$type] ?? '通知', 'body' => (string) $ann->body,
'status' => (string) $ann->status,
'published_at' => $ann->published_at === null ? null : (string) $ann->published_at,
'updated_at' => (string) $ann->updated_at];
}
}