CastsEnums : refactorize code

correction on code coments
This commit is contained in:
Jérémy Munsch 2021-09-11 22:47:20 +02:00
parent 1a5be20be2
commit e687db37e7
No known key found for this signature in database
GPG key ID: 677E1F9F80C16560

View file

@ -2,9 +2,13 @@
namespace Kwaadpepper\Enum\Traits;
use BadMethodCallException;
use Illuminate\Support\Facades\Log;
use Kwaadpepper\Enum\BaseEnum;
use TypeError;
/**
* @property array $attributes Laravel model attributes
* @property array $enumCasts Map attribute names to enum classes.
* @method bool hasCast(string $key, array|string|null $types = null)
* @method mixed castAttribute(string $key, mixed $value)
@ -38,27 +42,20 @@ trait CastsEnums
*/
public function setAttribute($key, $value)
{
if ($value !== null && $this->hasEnumCast($key)) {
/** @var \Kwaadpepper\Enum\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);
}
// try cast to int if is int
$value = is_numeric($value) && floatval(intval($value)) === floatval($value) ?
(int)$value : $value;
$this->attributes[$key] = $enum::make($value)->value;
try {
if ($enum = $this->castToEnum($key, $value) and $enum instanceof BaseEnum) {
$this->attributes[$key] = $enum->value;
return $this;
}
} catch (TypeError | BadMethodCallException $e) {
Log::debug(\sprintf('%s : trait CastEnums error, %s', __CLASS__, $e->getMessage()));
if (in_array(config('app.env'), ['debug', 'testing'])) {
throw $e;
}
return $this;
}
// @codeCoverageIgnoreStart
return parent::setAttribute($key, $value);
// @codeCoverageIgnoreEnd
}
/**
@ -75,7 +72,8 @@ trait CastsEnums
return false;
}
return array_key_exists($key, $this->enumCasts);
return array_key_exists($key, $this->enumCasts) and
is_subclass_of($this->enumCasts[$key], BaseEnum::class);
}
/**
@ -83,17 +81,31 @@ trait CastsEnums
*
* @param string $key
* @param mixed $value
* @return \Kwaadpepper\Enum\BaseEnum|null
* @return \Kwaadpepper\Enum\BaseEnum|mixed|null
* @throws TypeError — If anything else than string or int is used.
* @throws BadMethodCallException — If a matching definition cannot be found.
*/
protected function castToEnum($key, $value): ?BaseEnum
protected function castToEnum($key, $value)
{
if (
$value === null or
$value instanceof BaseEnum or
!isset($this->enumCasts[$key])
) {
return $value;
}
if ($this->hasCast($key)) {
$value = $this->castAttribute($key, $value);
}
// try cast to int
$value = (is_numeric($value) and floatval(intval($value)) === floatval($value)) ?
(int)$value : $value;
/** @var \Kwaadpepper\Enum\BaseEnum $enum */
$enum = $this->enumCasts[$key];
if ($value === null || $value instanceof BaseEnum) {
return $value;
} else {
return $enum::make($value);
}
return $enum::make($value);
}
}