swaggest / php-json-schema

High definition PHP structures with JSON-schema based validation
MIT License
451 stars 51 forks source link

Export properties with null as a value #85

Closed fabfischer closed 5 years ago

fabfischer commented 5 years ago

Hi,

I noticed that properties having null as a value are not exported. These properties are just missing in an exported JSON file. But I wanted/needed all these properties in my current project - so I created a "feature" for it.

You can trigger this behavior with an option, which is passed through to the jsonSerialize method. It's not the nicest way to control it, but I didn't find another way. Feedback very welcome.

Output without option: { "id": 123, "foo": "bar" }

Output with option: { "id": 123, "foo": "bar", "null_property": null }

codecov[bot] commented 5 years ago

Codecov Report

Merging #85 into master will increase coverage by 0.05%. The diff coverage is 100%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master      #85      +/-   ##
==========================================
+ Coverage   90.02%   90.08%   +0.05%     
==========================================
  Files          27       27              
  Lines        1604     1613       +9     
==========================================
+ Hits         1444     1453       +9     
  Misses        160      160
Impacted Files Coverage Δ
src/Structure/ClassStructureTrait.php 97.01% <100%> (+0.46%) :arrow_up:

Continue to review full report at Codecov.

Legend - Click here to learn more Δ = absolute <relative> (impact), ø = not affected, ? = missing data Powered by Codecov. Last update c1f3b05...7a200bc. Read the comment docs.

vearutop commented 5 years ago

Hi, thanks for this PR!

This PR fails phpstan check, because jsonSerialize() is defined in \JsonSerializable standard interface and does not accept parameters.

That could be fixed by moving the argument to a hidden instance property like here.

But I'm not sure that would be the best solution, my concern is that such flag has global impact on all properties (of all nested objects) being processed within export session. So such flag will not help in case null should be skipped for some particular property, but exported for all the rest.

Maybe a better solution would be to control nullability on property level, e.g. if property schema declares "type":["null","number"] then null is exported. Would such solution fit your use case?

Also it is currently possible to express nullability by using magical dynamic phpdoc @property, like here.

fabfischer commented 5 years ago

Hi, thank you for your response. I like your idea to use the type declaration in the schema. I changed my code to check whether a property can be null or not. If a property can be null, it is exported as null too.

I squashed all commits to have only one.

vearutop commented 5 years ago

Tagged v0.12.20.