Skip to content

Conversation

KorDum
Copy link

@KorDum KorDum commented Aug 8, 2025

This change includes two improvements:

  1. According to the JSON:API specification, the resource type is always a string (implying a non-empty string), which means that null is not allowed in the resource type.
  2. For implementing complex scenarios with Discriminator Map, it is more logical to embed the type at the resource data level, especially since the method contract allows you to not explicitly specify the resource type when forming the resource. See below for details.

Now you can implement scenarios like these:

final class FooTransformer extends TransformerAbstract
{
    public function transform(object $obj): array
    {
        return [
            'id' => '1',
            'type' => 'foo',
        ];
    }
}

final class BarTransformer extends TransformerAbstract
{
    public function transform(object $obj): array
    {
        return [
            'id' => '2',
            'type' => 'bar',
        ];
    }
}

final class MixedTransformer extends TransformerAbstract
{
    public function transform(object $obj): array
    {
        return match (true) {
            $obj instanceof Foo => new FooTransformer()->transform($obj),
            $obj instanceof Bar => new BarTransformer()->transform($obj),
            default => throw new InvalidArgumentException(),
        };
    }
}
{"data":[
    {"type":"foo","id":"1","attributes":{}},
    {"type":"bar","id":"2","attributes":{}}
]}

Also works with includes.

I think this change breaks backward compatibility and should be highlighted somehow.

@KorDum KorDum force-pushed the improve-json-api-serializer branch from e2ded29 to 64f8788 Compare August 8, 2025 10:11
@KorDum KorDum force-pushed the improve-json-api-serializer branch from 64f8788 to 489d24f Compare August 8, 2025 10:12
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