119 lines
2.9 KiB
PHP
119 lines
2.9 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Lib\ToolboxHelper;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Support\Facades\File;
|
|
|
|
class Product extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
/**
|
|
* Fillable fields.
|
|
*
|
|
* @var array
|
|
*/
|
|
#[\Override]
|
|
protected $fillable = [
|
|
'gamme_id',
|
|
'name',
|
|
'slug',
|
|
'description',
|
|
'picture1',
|
|
'alt_text_picture1',
|
|
'picture2',
|
|
'alt_text_picture2',
|
|
'picture3',
|
|
'alt_text_picture3',
|
|
'picture3_display',
|
|
'pictos',
|
|
'plusproduit',
|
|
'is_published',
|
|
'seo_title',
|
|
'seo_description',
|
|
'seo_keywords'
|
|
];
|
|
|
|
/**
|
|
* The "booted" method of the model.
|
|
*
|
|
* @return void
|
|
*/
|
|
protected static function boot(): void
|
|
{
|
|
static::creating(function (Product $product): void {
|
|
$product->updateImages($product);
|
|
});
|
|
|
|
static::updating(function (Product $product): void {
|
|
$product->updateImages($product);
|
|
});
|
|
|
|
static::deleted(function (Product $product): void {
|
|
$product->deleteImages($product, $product->picture1);
|
|
$product->deleteImages($product, $product->picture2);
|
|
$product->deleteImages($product, $product->picture3);
|
|
});
|
|
parent::boot();
|
|
}
|
|
|
|
/**
|
|
* Update images.
|
|
*
|
|
* @param Product $model
|
|
* @return void
|
|
*/
|
|
private static function updateImages(Product $model): void
|
|
{
|
|
if ($model->picture1) {
|
|
$model->picture1 = ToolboxHelper::storeImage($model->picture1, $model->getTable());
|
|
}
|
|
if ($model->picture2) {
|
|
$model->picture2 = ToolboxHelper::storeImage($model->picture2, $model->getTable());
|
|
}
|
|
if ($model->picture3) {
|
|
$model->picture3 = ToolboxHelper::storeImage($model->picture3, $model->getTable());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Delete images.
|
|
*
|
|
* @param Product $product
|
|
* @param string $target
|
|
* @return void
|
|
*/
|
|
private static function deleteImages(Product $product, string $target): void
|
|
{
|
|
if ($target) {
|
|
$urlTarget = public_path() . $target;
|
|
if ($urlTarget) {
|
|
if (File::exists($urlTarget)) {
|
|
File::delete($urlTarget);
|
|
}
|
|
}
|
|
}
|
|
$plusproduit = json_decode($product->plusproduit);
|
|
foreach ($plusproduit as $plus) {
|
|
$urlTarget = public_path() . $plus->url;
|
|
if ($urlTarget) {
|
|
if (File::exists($urlTarget)) {
|
|
File::delete($urlTarget);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get the Range that owns the product.
|
|
*
|
|
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
|
|
*/
|
|
public function gamme()
|
|
{
|
|
return $this->belongsTo(Gamme::class);
|
|
}
|
|
}
|