74 lines
2.2 KiB
PHP
74 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Concerns;
|
|
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Support\Str;
|
|
use Spatie\MediaLibrary\MediaCollections\Models\Media;
|
|
|
|
trait RegistersMedia
|
|
{
|
|
private function registerMedia(
|
|
Model $model,
|
|
string $s3Key,
|
|
string $collectionName,
|
|
array $generatedConversions = [],
|
|
?int $fileSize = null,
|
|
?string $mimeType = null,
|
|
?int $orderColumn = null,
|
|
?string $name = null,
|
|
): void {
|
|
$defaultName = pathinfo($s3Key, PATHINFO_FILENAME);
|
|
|
|
Media::create([
|
|
'model_type' => $model->getMorphClass(),
|
|
'model_id' => $model->id,
|
|
'uuid' => Str::uuid(),
|
|
'collection_name' => $collectionName,
|
|
'name' => $name ?? $defaultName,
|
|
'file_name' => $s3Key,
|
|
'mime_type' => $mimeType ?? 'image/jpeg',
|
|
'disk' => 's3',
|
|
'conversions_disk' => 's3',
|
|
'size' => $fileSize ?? 0,
|
|
'manipulations' => [],
|
|
'custom_properties' => [],
|
|
'generated_conversions' => $generatedConversions,
|
|
'responsive_images' => [],
|
|
'order_column' => $orderColumn ?? 1,
|
|
]);
|
|
}
|
|
|
|
private function registerMediaFromBase64(
|
|
Model $model,
|
|
string $data,
|
|
string $collectionName,
|
|
string $subdirectory,
|
|
array $generatedConversions = [],
|
|
): void {
|
|
if (str_starts_with($data, 'data:image')) {
|
|
$base64 = explode(',', $data)[1];
|
|
$imageData = base64_decode($base64);
|
|
$filename = $collectionName.'_'.time().'_'.uniqid().'.jpg';
|
|
$s3Key = $subdirectory.'/'.$filename;
|
|
|
|
app('filesystem')->disk('s3')->put($s3Key, $imageData);
|
|
$mimeType = 'image/jpeg';
|
|
$fileSize = strlen($imageData);
|
|
} else {
|
|
$s3Key = $data;
|
|
$mimeType = 'image/jpeg';
|
|
$fileSize = 0;
|
|
}
|
|
|
|
$this->registerMedia(
|
|
model: $model,
|
|
s3Key: $s3Key,
|
|
collectionName: $collectionName,
|
|
generatedConversions: $generatedConversions,
|
|
fileSize: $fileSize,
|
|
mimeType: $mimeType,
|
|
);
|
|
}
|
|
}
|