Files

125 lines
3.4 KiB
PHP
Raw Permalink Normal View History

<?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]);
}
}