Skip to content

PHP 8.1 Backed enums #4349

Closed
Closed
@bpolaszek

Description

@bpolaszek

Hello there,

PHP 8.1 is on its way and will bring a long awaited feature: Enums.
As I'm really looking forward for that feature to land, I was wondering how Api-Platform will handle enums, and I didn't see any commit or PR related to that feature so far, so I wanted to start a discussion about this.

From my point of view,

  • We should be able to list cases of an enum (GET / collection)
  • We should be able to list "properties" of an enum (GET / item) - enums don't have properties (except read-only name and value - and I don't think exposing name is relevant) but they can have methods which can be exposed as properties through Symfony's serializer
  • We should not be able to alter an enum (no POST / PUT / PATCH / DELETE - out of the box if possible)

I assume it should be easy to just add an ApiResource annotation on top of a Status enum to immediately expose:

  • GET /api/statuses
  • GET /api/statuses/{id}

Considering the following enum:

#[ApiResource]
enum Status: string
{
    case DRAFT = 'draft';
    case PUBLISHED = 'published';
}

I assume GET /api/statuses would return

{
  "@context": "/api/contexts/Status",
  "@id": "/api/statuses",
  "@type": "hydra:Collection",
  "hydra:member": [
    {
      "@id": "/api/statuses/draft",
      "@type": "Status",
      "value": "draft"
    },
    {
      "@id": "/api/statuses/published",
      "@type": "Status",
      "value": "published"
    }
  ]
}

Is that correct? Or do you plan to just return a list of values, like

{
  "@context": "\/api\/contexts\/Status",
  "@id": "\/api\/statuses",
  "@type": "hydra:Collection",
  "hydra:member": [
    "draft",
    "published"
  ]
}

?

I think the 1st one is more consistent, but that could also change the way we POST/PUT/PATCH entities.
Should we:

POST /api/posts
Content-Type: application/json

{
  "title": "foo",
  "status": "draft"
}

or

POST /api/posts
Content-Type: application/json

{
  "title": "foo",
  "status": "/api/statuses/draft"
}

?

I'm trying to get what direction you're taking on this so that I can anticipate a little on my developments - I'm working on something that will probably land on prod after PHP 8.1's release and I'd like the refactoring process to be as smooth as possible.

Maybe you already worked on this in background? WDYT?

Thanks!

NB: I'm only talking about backed enums here, I don't think normal enums can get in that scope.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions