Files
new_ine/app/Models/Traits/HasCovers.php
2021-10-09 13:12:45 +08:00

83 lines
2.0 KiB
PHP

<?php
namespace App\Models\Traits;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
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);
}
}
}