Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enum constraints are not added to response objects #608

Open
manuel-watchenterprise opened this issue Oct 28, 2024 · 4 comments
Open

Enum constraints are not added to response objects #608

manuel-watchenterprise opened this issue Oct 28, 2024 · 4 comments

Comments

@manuel-watchenterprise
Copy link
Contributor

manuel-watchenterprise commented Oct 28, 2024

Enum constraints (not backed!) are working fine for request objects, however, are not added to responses. Backed enums are working fine in responses as well.

/**
 * @mixin \App\Models\WatchCollectionItem
 */
class WatchResource extends BaseJsonResource
{
  public function toArray($request): array
  {
    return [
      /** @var OwnershipState */
      'ownership_state' => $this->ownership_state?->name,
    ];
  }
}

class WatchCollectionItem extends Model
{
  public function casts(): array
  {
    return [
      'ownership_state' => OwnershipState::class,
    ];
  }
}

enum OwnershipState
{
    case OWNING;
    case SOLD;
    case TRADED;
    case GIFTED;
    case LOST;
}

image

@romalytvynenko
Copy link
Member

@manuel-watchenterprise what is the expected result here?

@manuel-watchenterprise
Copy link
Contributor Author

Something like this:
image

@ikhbaaalll
Copy link

Something like this: image

you need to specify the value

enum MaritalEnum: string
{
    case Married = "Married";
    case Single = "Single";
    case Widow = "Widow";
    case Widowr = "Widowr";
}
$this->mergeWhen(collect($this->resource)?->get('marital') != null, [
    /** @var MaritalEnum */
    'marital' => collect($this->resource)?->get('marital'),
])

image

@manuel-watchenterprise
Copy link
Contributor Author

@ikhbaaalll thank you, I do appreciate.
Though I am aware that backed enums are working fine, this is why I reported that non-backed enums are not working as - in my opinion - expected. In requests both of them are recognised and handled, however, in responses backed enums only.

I could easily and quickly refactor my non-backed enums, I might will do that, but I believe these have to be handled. It's personal taste, but having backed enum just to have identical string value assigned to value as the name is, seems unnecessary to me.

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

No branches or pull requests

3 participants