Crell / Serde

Robust Serde (serialization/deserialization) library for PHP 8.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

FR: infer types from docblock

simPod opened this issue · comments

Detailed description

Docs mention similar snippet like this:

use Crell\Serde\Attributes as Serde;

class Results
{
    public function __construct(
        #[Serde\SequenceField(arrayType: Product::class)]
        public array $products,
    ) {}
}

Could it support docblocks so we don't have to add additional attributes?

use Crell\Serde\Attributes as Serde;

class Results
{
    public function __construct(
        /** @param array<Product> */
        public array $products,
    ) {}
}

Context

I'd prefer to keep my classes free of any attributes. I have already fully typed properties, e.g. collections are typed as array<Product> so there's no really a need for additional annotation since the type can be already inferred.

So I'd like

        /** @param array<Product> */
        public array $products,

work the same as public int $i.

Unfortunately that would require bringing in a docblock parser, which is a whole other ball of code on its own. Serde goes all-in on attributes specifically for that reason: The attribute parsing is built into the PHP engine, whereas using docblocks would require either some ugly string parsing hack or bringing in a larger existing library like Doctrine annotations. Not using Doctrine Annotations is a deliberate design goal for Serde.

This is exactly why attributes are such a good new feature: You don't need your own user-space parser anymore.

I might accept a patch that does one-off parsing of just @var if it's small and robust enough, but it's not something I am planning to work on myself.