90 lines
1.9 KiB
PHP
90 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace App\Models\Traits;
|
|
|
|
use Illuminate\Support\Facades\Storage;
|
|
use Illuminate\Support\Str;
|
|
use function collect;
|
|
|
|
trait HasCovers
|
|
{
|
|
|
|
/**
|
|
* Notes : 获取封面图片字段(单图)
|
|
*
|
|
* @Date : 2021/3/16 4:34 下午
|
|
* @Author : <Jason.C>
|
|
* @return string
|
|
*/
|
|
public function getCoverField(): string
|
|
{
|
|
return $this->cover_field ?? 'cover';
|
|
}
|
|
|
|
/**
|
|
* Notes : 获取图片字段(多图)
|
|
*
|
|
* @Date : 2021/3/16 4:35 下午
|
|
* @Author : <Jason.C>
|
|
* @return string
|
|
*/
|
|
public function getPicturesField(): string
|
|
{
|
|
return $this->pictures_field ?? 'pictures';
|
|
}
|
|
|
|
/**
|
|
* Notes : 解析单图地址
|
|
*
|
|
* @Date : 2021/3/16 4:54 下午
|
|
* @Author : <Jason.C>
|
|
* @return string
|
|
*/
|
|
public function getCoverUrlAttribute(): string
|
|
{
|
|
$cover = $this->getAttribute($this->getCoverField());
|
|
|
|
return $this->parseImageUrl($cover);
|
|
}
|
|
|
|
/**
|
|
* Notes : 解析多图地址
|
|
*
|
|
* @Date : 2021/3/16 4:54 下午
|
|
* @Author : <Jason.C>
|
|
* @return array
|
|
*/
|
|
public function getPicturesUrlAttribute(): array
|
|
{
|
|
$pictures = $this->getAttribute($this->getPicturesField());
|
|
|
|
if (empty($pictures)) {
|
|
return [];
|
|
}
|
|
|
|
return collect($pictures)->map(function ($picture) {
|
|
return $this->parseImageUrl($picture);
|
|
})->toArray();
|
|
}
|
|
|
|
/**
|
|
* Notes : 解析图片文件的实际展示地址
|
|
*
|
|
* @Date : 2021/3/16 4:53 下午
|
|
* @Author : <Jason.C>
|
|
* @param string|null $image
|
|
* @return string
|
|
*/
|
|
protected function parseImageUrl(?string $image): string
|
|
{
|
|
if (empty($image)) {
|
|
return '';
|
|
} elseif (Str::startsWith($image, 'http')) {
|
|
return $image;
|
|
} else {
|
|
return Storage::url($image);
|
|
}
|
|
}
|
|
|
|
}
|