for testing and deploying your application
for finding and fixing issues
for empowering human code reviews
<?php
namespace Spatie\Enum;
use Spatie\Enum\Exceptions\InvalidEnumError;
use Spatie\Enum\Exceptions\InvalidValueException;
trait HasEnums
{
/**
* @param $key
* @param \Spatie\Enum\Enum $enumObject
*
* @return mixed
*/
public function setAttribute($key, $enumObject)
if (! isset($this->enums[$key])) {
enums
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
class MyClass { } $x = new MyClass(); $x->foo = true;
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:
class MyClass { public $foo; } $x = new MyClass(); $x->foo = true;
return parent::setAttribute($key, $enumObject);
}
$enumClass = $this->enums[$key];
if (! is_a($enumObject, $enumClass)) {
throw InvalidEnumError::make(
static::class,
$key,
$enumClass,
get_class($enumObject)
);
$enumValue = $enumObject->getValue();
$mappedValue = $enumClass::$map[$enumValue] ?? null;
$this->attributes[$key] = $mappedValue ?? $enumValue;
attributes
return $this;
public function getAttribute($key)
return parent::getAttribute($key);
$storedEnumValue = $this->attributes[$key] ?? null;
try {
$enumObject = forward_static_call_array(
$enumClass . '::make',
[$storedEnumValue]
} catch (InvalidValueException $exception) {
$mappedEnumValue = array_search($storedEnumValue, $enumClass::$map ?? []);
if (! $mappedEnumValue) {
throw new InvalidValueException($storedEnumValue, $enumClass);
[$mappedEnumValue]
return $enumObject;
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: