ldc-legaulois/app/Traits/CastsEnums.php
Jérémy Munsch f38e95bce8 Migration fonctionnelle sur :
- article_category
 - article
 - eleveur
 - eleveurs_sites
 - survey_response
 - fos_user
 - aimant_user
 - content_ocb
 - encemoment_fiche
 - encemoment_strates
 - gamme
 - home_slider
 - home_mini_slider
 - moment_consommation
 - pays
 - type_viande
 - societe
 - famille_vente
 - produit
 - recipe
 - menu
 - produit (update)
 - pictos
 - pictosproducts
 - inco_composition
 - qrcode
 - product_slider
 - recipe Articles
 - reduction
 - products reductions
 - saga
 - user_favorite_recipe

Introduces Enum system caster and trait

Html Colors auto cast for HomeSliderPictures and Ranges

All migrations struct, data and model traits except HomeSliderPicture

Days enum system and HomeSliderPicture migration
2021-02-08 09:47:36 +01:00

93 lines
2.2 KiB
PHP

<?php
namespace App\Traits;
use App\Enums\BaseEnum;
/**
* @property array $enumCasts Map attribute names to enum classes.
*/
trait CastsEnums
{
/**
* Get a plain attribute (not a relationship).
*
* @param string $key
* @return mixed
*/
public function getAttributeValue($key)
{
$value = parent::getAttributeValue($key);
if ($this->hasEnumCast($key)) {
$value = $this->castToEnum($key, $value);
}
return $value;
}
/**
* Set a given attribute on the model.
*
* @param string $key
* @param mixed $value
* @return $this
*/
public function setAttribute($key, $value)
{
if ($value !== null && $this->hasEnumCast($key)) {
/** @var \App\Enums\BaseEnum $enum */
$enum = $this->enumCasts[$key];
if ($value instanceof $enum) {
$this->attributes[$key] = $value->value;
} else {
if ($this->hasCast($key)) {
$value = $this->castAttribute($key, $value);
}
$this->attributes[$key] = $enum::make($value)->value;
}
return $this;
}
return parent::setAttribute($key, $value);
}
/**
* Determine whether an attribute should be cast to a enum.
*
* @param string $key
* @return bool
*/
public function hasEnumCast($key): bool
{
// This can happen if this trait is added to the model
// but no enum casts have been added yet
if ($this->enumCasts === null) {
return false;
}
return array_key_exists($key, $this->enumCasts);
}
/**
* Casts the given key to an enum instance
*
* @param string $key
* @param mixed $value
* @return \App\Enums\BaseEnum|null
*/
protected function castToEnum($key, $value): ?BaseEnum
{
/** @var \App\Enums\BaseEnum $enum */
$enum = $this->enumCasts[$key];
if ($value === null || $value instanceof BaseEnum) {
return $value;
} else {
return $enum::make($value);
}
}
}