Skip to content

Conversation

iamrgroot
Copy link
Contributor

@iamrgroot iamrgroot commented Oct 3, 2025

This PR attempts to fix an issue I am having while using custom TransformationContext classes

Use-case

I would like to add some meta data to the transformed Data and DataCollections (including all nested items), but only in some scenarios. For me this is when transforming a Data class to Reponse. For example

class UserData extends Data
{
    public function __construct(
        public string $id,
        public string $name,
    ) {}
}

Should result in the response:

{
  "data": {
    "id": "id",
    "name": "name"
  },
  "meta": {
     "key": "value"
  }
}

Additional data appends the data to the data part so I ruled that out, but I figured out I could overwrite the TransformedDataCollectableResolver and TransformedDataResolver and use a custom TransformationContext. Like this:

class ResponseTransformationContext extends TransformationContext
{}

class ResponseDataCollectableResolver extends TransformedDataCollectableResolver
{
    public function execute(
        iterable $items,
        TransformationContext $context,
    ) {
        $transformed = parent::execute($items, $context);

        if ($context instanceof ResponseTransformationContext) {
            // Append stuff to the transformed data :)
        }

        return $transformed;
    }
}

// Same same for the TransformedDataResolver

// Call it like this:
$data->transform(new ResponseTransformationContext());

This works!

The problem

The problem is that it only works on the top level and not on nested data structures. This is because when properties are resolved in the VisibleDataFieldsResolver, the $transformationContext is newly created as TransformationContext and not as my custom ResponseTransformationContext.

The solution

Changing the VisibleDataFieldsResolver to clone (and reset) the current $transformationContext instead of creating it fixes my issue.

As far as I saw this is the only place that the context gets created, besides the initial creation if not provided.

If you see a better solution for my situation, please let me know!

@iamrgroot iamrgroot marked this pull request as ready for review October 3, 2025 15:14
@iamrgroot iamrgroot changed the title fix: clone context instead of creating a new one fix: clone transformation context instead of creating a new one Oct 3, 2025
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