Files
lgp-admin-plus-api/app/Service/business/CarouselService.php
LQ bcf54c2727 初始化
缺陷:主题配色需要优化整体的同风格
2026-08-14 23:21:21 +08:00

125 lines
3.4 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Service\business;
use App\BaseApp\BaseService;
use App\Models\business\CarouselModel;
use App\Service\common\MediaUrlService;
use Exception;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
/**
* 小程序轮播图
*
* 老 CarouselService 是从 CategoryService 复制来的option() 去查 carousel 表上并不存在的
* name / pid 两列,调用即报错。这里按轮播图自己的字段重写。
*/
class CarouselService extends BaseService
{
private MediaUrlService $media;
public function __construct()
{
parent::__construct();
$this->model = CarouselModel::class;
$this->selectField = ['id', 'url', 'to_path', 'sort', 'status', 'created_at', 'updated_at'];
$this->queryField = ['to_path' => 'like', 'status' => '='];
$this->orderBy = ['name' => 'sort', 'sort' => 'asc'];
$this->media = MediaUrlService::getInstance();
}
/**
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function list(): array
{
$result = $this->getPageList();
$this->media->publicEach($result['items'], ['url']);
return $result;
}
public function option(): mixed
{
$rows = CarouselModel::where('deleted_at', 0)
->orderBy('sort')
->get(['id', 'url', 'to_path', 'sort'])
->toArray();
$this->media->publicEach($rows, ['url']);
return $rows;
}
/**
* @throws Exception
*/
public function detail($id): mixed
{
$info = $this->getDetail($id);
$info->url = $this->media->toPublic($info->url);
return $info;
}
/**
* 新增:支持一次选多张图批量建轮播
* @throws Exception
*/
public function create($params): mixed
{
$urls = $params['url'] ?? '';
$urls = is_array($urls) ? $urls : [$urls];
$now = time();
$sort = (int) ($params['sort'] ?? 0);
$rows = [];
foreach ($urls as $index => $url) {
$url = $this->media->toStorage(is_string($url) ? $url : '');
if ($url === '') {
continue;
}
$rows[] = [
'url' => $url,
'to_path' => (string) ($params['to_path'] ?? ''),
'sort' => $sort + $index,
// 缺省显示;前端可传 status批量建时统一用同一状态
'status' => (int) ($params['status'] ?? 0),
'created_at' => $now,
];
}
if (empty($rows)) {
$this->utils->errorThrow('请上传轮播图');
}
if (count($rows) === 1) {
return $this->insert($rows[0]);
}
return CarouselModel::insert($rows);
}
/**
* @throws Exception
*/
public function update($id, $params): mixed
{
if (array_key_exists('url', $params)) {
$params['url'] = $this->media->firstOf($params['url']);
}
return $this->save($id, $params);
}
/**
* @throws Exception
*/
public function delete($id): mixed
{
return $this->del(is_array($id) ? $id : [$id]);
}
/**
* @throws Exception
*/
public function status($id, $status): mixed
{
return $this->save($id, ['status' => (int) $status]);
}
}