schmittjoh / serializer

Library for (de-)serializing data of any complexity (supports JSON, and XML)
http://jmsyst.com/libs/serializer
MIT License
2.32k stars 589 forks source link

feat: use generic types for deserialization #1453

Closed scyzoryck closed 1 year ago

scyzoryck commented 1 year ago
Q A
Bug fix? no
New feature? yes
Doc updated no
BC breaks? no
Deprecations? no
Tests pass? yes
Fixed tickets
License MIT

It looks like right now to have a proper type hints for it required additional plugin. Inspired by: https://phpstan.org/blog/generics-by-examples it allowed to use generics for type hinting.

Debug file

<?php

declare(strict_types=1);

namespace JMS\Serializer\Tests;

use JMS\Serializer\SerializerBuilder;
use JMS\Serializer\Tests\Fixtures\Author;

$serializer = SerializerBuilder::create()->build();
$d = $serializer->deserialize('{}', Author::class, 'json' );
\PHPStan\dumpType($d); // MyDerivative :)

$serializer = SerializerBuilder::create()->build();
$d = $serializer->deserialize('{}', Author::class . '[]', 'json' );
\PHPStan\dumpType($d); //

Before

 ------ ----------------------------------------------------- 
  Line   PHPStanTypesTest.php                                 
 ------ ----------------------------------------------------- 
  13     Dumped type: mixed
  18     Dumped type: mixed
 ------ ----------------------------------------------------- 

After

 ------ ----------------------------------------------------- 
  Line   PHPStanTypesTest.php                                 
 ------ ----------------------------------------------------- 
  13     Dumped type: JMS\Serializer\Tests\Fixtures\Author    
  18     Dumped type: JMS\Serializer\Tests\Fixtures\Author[]  
 ------ ----------------------------------------------------- 
goetas commented 1 year ago

This was already implemented in the past and reverted. It does not work well when the de-serialized type is an array or objects.

I use this extension to provide the return type in this case https://github.com/goetas/jms-serializer-phpstan-extension