Exclude by group
| Q | A |
|---|---|
| Bug report? | no |
| Feature request? | no |
| BC Break report? | no |
| RFC? | maybe |
Hey there, is it possible to exclude attributes if the context contains a certain group? I am searching for an annotation that does the exact opposite of @Groups(). I studied the code base extensively but I did not find any annotation that does this. @Exclude(if="...") seems promising to me but I can't seem to access the groups from within the expression language statement. If this is not possible, is there interest for a PR that adds this annotation or is there a good reason not to allow users to exclude by group? Regards, Hendrik
are you referring to something as https://github.com/schmittjoh/serializer/issues/424 ?
if i'm not mistaken, you would like to exclude an attribute if a specific group is present... right?
Currently there are many exclusion strategies already available, and this can be easily emulated using context attributes as:
$context->attributes->set("foo", true)
and having
@Exclude(if="context.attributes.has('foo')")
Are other advantages of your proposal?
Yes, #424 sounds similar.
Excluding via a context attribute is not the perfect solution in my case. It sounds like it could work by adding "group copies" in the context right next to the actual groups but it is a dirty hack nevertheless. First, I always have to store every value twice in the context since I need the groups for other tasks as well. Second, I have quite a complex entity structure and require this functionality at multiple locations. A dedicated annotation for this task would make the code much more readable.
In a nutshell, I agree that there are some exclusion strategies that can be used to get to the same results as "exclusion by group" but in my opinion the resulting code is much more complex and harder to extend.
I do not have really a strong opinion on this. I'm more worried on making the serializer code bigger.
The serializer offer "groups" that are "inclusions, while this will be some kind of "groups" but with inclusion.
I do not know if it can help you make a decision, but I personally just discovered that groups could not be used for deserialization limitations.
I emulated the way @goetas suggested above and it works great (thanks). But I am using nelmio/api-doc-bundle to render an example of a body. They only have the groups options to configure the view rendered so I think they did not think of something like this either.
All that to say, I personally think if everyone must be surprised by the functionality, then tweak it to work as expected. It might be a good indicator that the functionality should be possible.
In case someone else stumbles across this... @Exclude(if="context.hasAttribute('foo')") appears to be more current.