ldc-showroom-bo/app/Models/Font.php
2025-05-27 09:11:43 +02:00

111 lines
3.6 KiB
PHP

<?php
namespace App\Models;
use App\Traits\Models\ActivityLog;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Stancl\Tenancy\Database\Concerns\BelongsToTenant;
use Uwil\LaravelCommon\Helpers\FileHelper;
/**
* @property string $font_name The slugified font name.
* @property string|null $font The font path.
* @property string $tenant_id Id of the related tenant.
* @property-read \Illuminate\Support\Carbon $created_at Created date.
* @property-read \Illuminate\Support\Carbon $updated_at Updated date.
*/
class Font extends Model
{
use HasFactory;
use BelongsToTenant;
use ActivityLog;
/**
* Default available fonts
*/
public const DEFAULT_FONTS = ['serif', 'sans-serif'];
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'font_name',
'font',
'tenant_id',
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted(): void
{
static::creating(function (self $model) {
// * ASSERTIONS
self::assertFontIsWoff2($model->font);
// * TRANSFORMATIONS
if ($model->font) {
$model->font = FileHelper::storeFile($model, $model->font, true, prefix: $model->tenant_id);
$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
self::assertFontIsWoff2($model->font);
// * TRANSFORMATIONS
if ($model->font) {
$model->font = FileHelper::storeFile($model, $model->font, true, prefix: $model->tenant_id);
$font_basename = Str::of(\pathinfo($model->font, \PATHINFO_BASENAME))->explode('.')->get(0);
$model->font_name = Str::slug($font_basename);
}
});
static::updated(function (self $model) {
FileHelper::removeOldFile($model, 'font');
});
static::deleted(function (self $model) {
FileHelper::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;
}
}
}