When adding additional attributes in serialization listeners, is there a way to detect the active serialization groups?
This is how I do it:
public function onPostSerialize(ObjectEvent $event)
{
// Get the actual object being serialized
$object = $event->getObject();
$context = $event->getContext();
// Try to get the serialization group from the context.
try {
$groups = $context->attributes->get('groups')->get();
} catch (\RuntimeException $e) {
$groups = [];
}
// Don't execute this listener when not in mustBeThisGroup
if (!in_array('mustBeThisGroup', $groups)) {
return;
}
// <Listener logic here>
}
But I would agree that there should be a nicer way for this.
@Sander-Toonen thanks for the feedback. i've come up with this helper in my serializers:
/**
* @param SerializationContext $context
* @param $group
* @return bool
*/
private function isGroupActive(SerializationContext $context, $group)
{
return $this->areGroupsActive($context, [$group]);
}
/**
* @param SerializationContext $context
* @param array $serializationGroups
* @return bool
*/
private function areGroupsActive(SerializationContext $context, array $serializationGroups)
{
/** @var Some $groupContext */
$groupContext = $context->attributes->get('groups');
if ($groupContext->isDefined()) {
$groups = $groupContext->get();
if (is_array($groups)) {
foreach ($serializationGroups as $group) {
if (in_array($group, $groups)) {
return true;
}
}
}
}
return false;
}
Most helpful comment
@Sander-Toonen thanks for the feedback. i've come up with this helper in my serializers: