square / pjson

JSON <=> PHP8+ objects serialization / deserialization library
Apache License 2.0
111 stars 8 forks source link

Allow passing in flags and depth parameters to json_encode() and json_decode() #11

Closed szainmehdi closed 2 years ago

szainmehdi commented 2 years ago

Allow passing flags and depth params to toJson(), toJsonList(), fromJsonString(), and listFromJsonString() methods.

Felt like this was missing. A sample use case might be to pass in JSON_PRETTY_PRINT for readability.

(new Schedule(1, 2))->toJson(flags: JSON_PRETTY_PRINT);

Default JSON_THROW_ON_ERROR flag for JSON serialization This was being done for deserialization but not for serialization.

Added tests for the above

Added PHPStan Extension Depending on way a class was set up, PHPStan would complain about properties being written to but never read from.

class Item
{
    public function __construct(
        #[Json]
        private string $id,
    ) {}
}

This perfectly valid use case would throw a PHPStan error like this:

Example PHPStan Error:
 ------ --------------------------------------------------------------------------------------------
  Line   src/Item.php
 ------ --------------------------------------------------------------------------------------------
  10     Property Item@src/Item.php:10::$id is never read, only written.
         💡 See: https://phpstan.org/developing-extensions/always-read-written-properties
 ------ --------------------------------------------------------------------------------------------

Allowing developers to simply add the PHPStan extension defined in this package to their phpstan.neon file helps eliminate these issues and allows us to expand on deeper PHPStan integration in the future.