Skip to content

Conversation

gigerIT
Copy link
Contributor

@gigerIT gigerIT commented Aug 6, 2025

Description

Adds support for casting a BackedEnum from another BackedEnum instance in EnumCast.

Previously, when attempting to cast from one enum type to another (e.g., from an internal enum to an API enum), the EnumCast would fail because it didn't handle BackedEnum instances as source values. This change extracts the scalar backing value using ->value when the source is a BackedEnum, enabling seamless enum to enum casting.

Use Case

This functionality is particularly useful when you have different enum granularities between internal models and API responses. For example:

  • Internal systems may use detailed enums with many specific cases for business logic
  • API responses may expose simplified enums with fewer, grouped cases for cleaner external contracts

Changes

  • Modified EnumCast::castValue() to check if $value instanceof \BackedEnum
  • Extract scalar value using $value->value before calling $type::from()
  • Maintains backward compatibility for all existing use cases

Example

// Internal enum with detailed vehicle types
enum InternalVehicleType: string
{
    case BICYCLE = 'bicycle';
    case MOTORBIKE = 'motorbike';
    case MOTORBIKE_SIDECAR = 'motorbikeWithSideCar';
    case CAR = 'car';
    case VAN = 'van';
    case MINIBUS = 'minibus';
    case CAMPER = 'camper';
    case VEHICLE_COMBINATION = 'vehicleCombination';
}

// Simplified API enum with fewer types
enum ApiVehicleType: string
{
    case BICYCLE = 'bicycle';
    case MOTORCYCLE = 'motorcycle';
    case CAR = 'car';
    case CAMPER = 'camper';
}

// API response data class
class VehicleApiResponse extends Data {
    public function __construct(
        public string $id,
        public ApiVehicleType $type,
    ) {}
}


$internalType = InternalVehicleType::MOTORBIKE;

// Previously would fail, now works:
$response = VehicleApiResponse::from([
    'id' => '123',
    'type' => $internalType  // Converts InternalVehicleType::MOTORBIKE to ApiVehicleType::MOTORCYCLE
]);

This change makes the package more flexible when working with enum transformations between different enum types.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant