ldc-showroom-bo/app/Models/Font.php

99 lines
3 KiB
PHP

<?php
namespace App\Models;
use App\Lib\Helpers\FileStorageHelper;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class Font extends Model
{
use HasFactory;
/**
* Default available fonts
*/
public const DEFAULT_FONTS = ['serif', 'sans-serif'];
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'font_name',
'font',
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted(): void
{
static::creating(function (self $model) {
// * ASSERTIONS
static::assertFontIsWoff2($model->font);
// * TRANSFORMATIONS
if ($model->font) {
$model->font = FileStorageHelper::storeFile($model, $model->font, true);
$font_basename = Str::of(\pathinfo($model->font, \PATHINFO_BASENAME))->explode('.')->get(0);
$model->font_name = Str::slug($font_basename);
}
});
static::updating(function (self $model) {
// * ASSERTIONS
static::assertFontIsWoff2($model->font);
// * TRANSFORMATIONS
if ($model->font) {
$model->font = FileStorageHelper::storeFile($model, $model->font, true);
$font_basename = Str::of(\pathinfo($model->font, \PATHINFO_BASENAME))->explode('.')->get(0);
$model->font_name = Str::slug($font_basename);
}
});
static::updated(function (self $model) {
FileStorageHelper::removeOldFile($model, 'font');
});
static::deleted(function (self $model) {
FileStorageHelper::removeFile($model, 'font');
});
}
// * METHODS
/**
* Assert font is Woff2
*
* @param \Illuminate\Http\UploadedFile|\SplFileInfo|string|null $font
* @return void
* @throws \Illuminate\Validation\ValidationException If font is not Woff 2 file type.
*/
private static function assertFontIsWoff2(
\Illuminate\Http\UploadedFile|\SplFileInfo|string|null $font
): void {
$exception = ValidationException::withMessages(['font' => trans(
'La police doit être au format Woff2, utilisez transfonter.org'
)]);
if (!$font) {
return;
}
if (is_string($font) and Str::of($font)->lower()->explode('.')->last() !== 'woff2') {
throw $exception;
}
if ($font instanceof \Illuminate\Http\UploadedFile and $font->getMimeType() !== 'font/woff2') {
throw $exception;
}
if (
!($font instanceof \Illuminate\Http\UploadedFile) and
$font instanceof \SplFileInfo and
Str::lower($font->getExtension()) !== 'woff2'
) {
throw $exception;
}
}
}