From 3541bf31ebce84337f8586f372c44759d51086ec Mon Sep 17 00:00:00 2001 From: lonesski Date: Fri, 11 Dec 2020 18:51:05 +0200 Subject: [PATCH] breaking fixes: leave only enum class --- src/CastStringEnums.php | 101 ---------------------------------------- src/StringEnum.php | 7 ++- 2 files changed, 5 insertions(+), 103 deletions(-) delete mode 100644 src/CastStringEnums.php diff --git a/src/CastStringEnums.php b/src/CastStringEnums.php deleted file mode 100644 index 1d103c5..0000000 --- a/src/CastStringEnums.php +++ /dev/null @@ -1,101 +0,0 @@ -hasEnumCast($key)) { - $value = $this->castToEnum($key, $value); - } - - return $value; - } - - /** - * Set a given attribute on the model. - * - * @param string $key - * @param mixed $value - * @return self - */ - public function setAttribute($key, $value) - { - if ($value !== null && $this->hasEnumCast($key)) { - $enum = $this->casts[$key]; - - if ($value instanceof $enum) { - $this->attributes[$key] = $value->value; - } else { - /** @var Enum $enum */ - if (is_string($value) && !$enum::hasKey($value)) { - throw new InvalidEnumKeyException($key, $enum); - } elseif (is_integer($value) && !$enum::hasValue($value)) { - throw new InvalidEnumMemberException($value, new $enum($value)); - } - - $this->attributes[$key] = $enum::coerce($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->casts === null) { - return false; - } - if (isset($this->casts[$key]) && !is_subclass_of($this->casts[$key], StringEnum::class)) { - return false; - } - - return array_key_exists($key, $this->casts); - } - - /** - * Casts the given key to an enum instance - * - * @param string $key - * @param mixed $value - * @return Enum|null - */ - protected function castToEnum($key, $value): ?Enum - { - /** @var Enum $enum */ - $enum = $this->casts[$key]; - - if ($value === null || $value instanceof Enum) { - return $value; - } else { - return $enum::fromValue($value); - } - } -} diff --git a/src/StringEnum.php b/src/StringEnum.php index 35c6e39..2a4829d 100644 --- a/src/StringEnum.php +++ b/src/StringEnum.php @@ -11,8 +11,11 @@ public function toArray() return $this->key; } - public function __toString(): string + public static function parseDatabase($value) { - return $this->key; + if (self::hasKey($value)) { + return self::fromKey($value)->value; + } + return parent::parseDatabase($value); } }