schmittjoh / serializer

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

Inline virtual property #1558

Open Bilge opened 2 months ago

Bilge commented 2 months ago
Q A
Bug report? yes
Feature request? yes
BC Break report? no
RFC? no

How is one supposed to inline a virtual property? The following does not work:

#[Serializer\VirtualProperty(name: 'xD', exp: 'object.format("c")', options: [[Serializer\Inline::class, []]])]
class Foo extends \DateTimeImmutable { ... }

(Aside, it shouldn't be necessary to specify a name for an inlined property, nor should it be necessary to specify an empty array after the inline class).

Expected Result

Actual Result

scyzoryck commented 2 months ago

Hi. Can you provide full working example of the code that you are trying to execute and achieve? In general you are trying to Inline the property that has string type - when Inline was designed to work with nested objects. If you think that we are missing some feature feel free to provide some Pull Request with changes. I will be glad to help to add this code to the next release.

Best Marcin.

Bilge commented 2 months ago

The purpose of what I was trying to achieve is just to have an object be represented as some value, without having to specify in everything that consumes it how to represent it. With VirtualProperty and a bunch of Excludes as necessary, we can represent the object as a single key/value pair, but I just want a value with no key (i.e. the formatted date of the DateTimeImmutable object).

scyzoryck commented 2 months ago

I would suggest to use custom handler for such classes - see DateHandler as an example. I believe it will be an easier solution to maintain in a long term but also better from performance point of view.

Best Marcin

Bilge commented 2 months ago

Perhaps DateHandler should automatically apply to objects extending DateTime/DateTimeImmutable, instead of only matching the class names verbatim.

scyzoryck commented 1 month ago

Handlers are meant to subscribe to specific class only - they do not apply to the child classes. Event listeners can apply to child classes and interfaces.