93 lines
3 KiB
PHP
93 lines
3 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Lib\Utils;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
class Gamme extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
protected $fillable = [
|
|
'parent_gamme_id',
|
|
'title',
|
|
'slug',
|
|
'text',
|
|
'color',
|
|
'picture',
|
|
'alt_text_picture',
|
|
'banner',
|
|
'alt_text_banner',
|
|
];
|
|
|
|
protected static function boot()
|
|
{
|
|
static::creating(function (Gamme $gamme) {
|
|
if ($gamme->picture) {
|
|
$gamme->picture = Utils::storeImage($gamme->picture, $gamme->getTable());
|
|
}
|
|
if ($gamme->banner) {
|
|
$gamme->banner = Utils::storeImage($gamme->banner, $gamme->getTable());
|
|
}
|
|
|
|
if ($gamme->parent_gamme_id != null) {
|
|
// Si Creation gamme enfant sans enfant, alors il faut update sa couleur selon celle du parent
|
|
$gamme->color = Gamme::whereId($gamme->parent_gamme_id)->select(['color'])->first()->color;
|
|
}
|
|
});
|
|
|
|
static::updating(function (Gamme $gamme) {
|
|
if ($gamme->picture) {
|
|
$gamme->picture = Utils::storeImage($gamme->picture, $gamme->getTable());
|
|
}
|
|
if ($gamme->banner) {
|
|
$gamme->banner = Utils::storeImage($gamme->banner, $gamme->getTable());
|
|
}
|
|
if ($gamme->parent_gamme_id === null) {
|
|
// Si Update gamme parente, alors il faut update la couleur des enfants
|
|
Gamme::whereParentGammeId($gamme->id)
|
|
->update(['color' => $gamme->color]);
|
|
} elseif ($gamme->childGammes()->exists()) {
|
|
/**
|
|
* Si Update gamme enfant qui a des enfants,
|
|
* alors il faut update sa couleur selon celle du parent
|
|
* et vider l'association parent/enfant des petits enfants
|
|
*/
|
|
$gamme->color = Gamme::whereId($gamme->parent_gamme_id)->select(['color'])->first()->color;
|
|
Gamme::whereParentGammeId($gamme->id)
|
|
->update(['parent_gamme_id' => null]);
|
|
} else {
|
|
// Si Update gamme enfant sans enfant, alors il faut update sa couleur selon celle du parent
|
|
$gamme->color = Gamme::whereId($gamme->parent_gamme_id)->select(['color'])->first()->color;
|
|
}
|
|
});
|
|
parent::boot();
|
|
}
|
|
|
|
public function getRgbaColorAttribute()
|
|
{
|
|
$color = $this->color;
|
|
|
|
if (!$color) {
|
|
return '';
|
|
}
|
|
if ($color[0] == '#') {
|
|
$color = substr($color, 1);
|
|
}
|
|
list($r, $g, $b) = array_map("hexdec", str_split($color, (strlen($color) / 3)));
|
|
|
|
return "rgba($r,$g,$b,.8)";
|
|
}
|
|
|
|
public function childGammes()
|
|
{
|
|
return $this->hasMany(Gamme::class, 'parent_gamme_id');
|
|
}
|
|
|
|
public function parentGamme()
|
|
{
|
|
return $this->belongsTo(Gamme::class);
|
|
}
|
|
}
|