Skip to content

Commit

Permalink
- default datetime format is now W3C (like "1981-02-04T16:17:18+02:00")
Browse files Browse the repository at this point in the history
- JsonSettings now union of JsonSerializeSettings and JsonDeserializeSettings
- new Setting "SkipNull"
- new Setting "SkipEmptyArray"
  • Loading branch information
peterGdot committed Aug 7, 2024
1 parent d51b5b2 commit e61434f
Show file tree
Hide file tree
Showing 13 changed files with 119 additions and 107 deletions.
3 changes: 2 additions & 1 deletion .gitattributes
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
demos/ export-ignore
demos/ export-ignore
.gitattributes
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "pyther/json",
"description": "JSON to/from model (de)serialization",
"description": "A lightweight (de)serializer between json strings and data models.",
"type": "library",
"keywords": [
"JSON",
Expand Down
6 changes: 5 additions & 1 deletion demos/Models/TypesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,12 @@ class TypesTest {
* @var integer|null
*/
public $intNullableByHint;


#[JsonType(\int::class)]
public $intByMeta;

public ?string $nullValue = null;

#[JsonType(\int::class)]
public array $emptyArray = [];
}
2 changes: 1 addition & 1 deletion demos/data/types.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"StringPropertyNullable": "abc",
"IntOrStringProperty": "abc123",
"IntOrStringPropertyNullable": "abc123",
"DateTimeProperty": "1981-02-04T16:17:18+",
"DateTimeProperty": "1981-02-04T16:17:18+02:00",
"DateTimePropertyByMeta": "04\/02\/1981",
"OrderItem": {
"Sku": "123-456-789",
Expand Down
7 changes: 3 additions & 4 deletions demos/enums.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@

use JsonException;
use Pyther\Json\Json;
use Pyther\Json\JsonSerializeSettings;
use Pyther\Json\Attributes\JsonEnum;
use Pyther\Json\JsonDeserializeSettings;
use Pyther\Json\JsonSettings;
use Pyther\Json\NamingPolicies\CamelToPascalNamingPolicy;
use Pyther\Json\Types\EnumFormat;

Expand Down Expand Up @@ -89,14 +88,14 @@ class EnumTest {
}

function serializeTest($object): string {
$settings = new JsonSerializeSettings();
$settings = new JsonSettings();
$settings->setEnumFormat(EnumFormat::Name);
$settings->setNamingPolicy(new CamelToPascalNamingPolicy());
return Json::serialize($object, $settings);
}

function deserializeTest(string $json): EnumTest {
$settings = new JsonDeserializeSettings();
$settings = new JsonSettings();
$settings->setNamingPolicy(new CamelToPascalNamingPolicy());
return Json::deserialize($json, EnumTest::class, $settings);
}
Expand Down
11 changes: 6 additions & 5 deletions demos/types.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
use Demo\Models\TypesTest;
use Pyther\Json\Exceptions\JsonException;
use Pyther\Json\Json;
use Pyther\Json\JsonDeserializeSettings;
use Pyther\Json\JsonSerializeSettings;
use Pyther\Json\JsonSettings;
use Pyther\Json\NamingPolicies\CamelToPascalNamingPolicy;
use Pyther\Json\Types\EnumFormat;

Expand All @@ -22,7 +21,7 @@
$obj = deserializeTest(file_get_contents("data/types.json"));
echo "Object:\n";
var_dump($obj);

// serialize
$json = serializeTest($obj);
echo "\n\nJSON:\n";
Expand All @@ -35,14 +34,16 @@
}

function serializeTest($object): string {
$settings = new JsonSerializeSettings();
$settings = new JsonSettings();
$settings->setEnumFormat(EnumFormat::Name);
$settings->setNamingPolicy(new CamelToPascalNamingPolicy());
$settings->setSkipNull(true);
$settings->setSkipEmptyArray(true);
return Json::serialize($object, $settings);
}

function deserializeTest(string $json): TypesTest {
$settings = new JsonDeserializeSettings();
$settings = new JsonSettings();
$settings->setNamingPolicy(new CamelToPascalNamingPolicy());
return Json::deserialize($json, TypesTest::class, $settings);
}
14 changes: 11 additions & 3 deletions readme.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,28 @@
# Pyther.Json

A lightweight JSON (de)serializer between json and a data model with the following features:
A lightweight (de)serializer between json strings and data models with the following features:

- support for nested arrays and objects
- pre defined or custom naming policies
- support for basic or backed enumerations.
- meta/attribute support for
- property renaming
- property exclusion
- (array) type
- (array) data type
- datetime format
- enum format
- several settings like
- include protected properties
- skip null values
- skip empty arrays
- enum format
- and more ...
- takes documentation "@var" hints into account
- no external dependencies
- straightforward to use

Requirements:
- PHP >= 8.1
- PHP 8.1+

## Examples:

Expand Down
2 changes: 1 addition & 1 deletion src/BaseExecuter.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ abstract class BaseExecuter

function __construct(?JsonSettings $settings = null)
{
$this->settings = $settings;
$this->settings = $settings ?? new JsonSettings();
}

/**
Expand Down
10 changes: 0 additions & 10 deletions src/JsonDeserializeSettings.php

This file was deleted.

8 changes: 0 additions & 8 deletions src/JsonDeserializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,8 @@
use Pyther\Json\Attributes\JsonDateTime;
use Pyther\Json\Exceptions\JsonException;

/**
* @property JsonDeserializeSettings $settings
*/
class JsonDeserializer extends BaseExecuter
{
function __construct(?JsonDeserializeSettings $settings = null)
{
parent::__construct($settings ?? new JsonDeserializeSettings());
}

/**
* Deserialize a json string or a deserialized json array into a class object.
*
Expand Down
59 changes: 0 additions & 59 deletions src/JsonSerializeSettings.php

This file was deleted.

11 changes: 3 additions & 8 deletions src/JsonSerializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,8 @@
use Pyther\Json\Attributes\JsonEnum;
use Pyther\Json\Types\EnumFormat;

/**
* @property JsonSerializeSettings $settings
*/
class JsonSerializer extends BaseExecuter
{
function __construct(?JsonSerializeSettings $settings = null)
{
parent::__construct($settings ?? new JsonSerializeSettings());
}

/**
* Serialize an object or array the the encoded json version.
*
Expand Down Expand Up @@ -72,12 +64,15 @@ private function serializeObject(object $object): ?array
$typeInfo = new TypeInfo($prop);

$value = $this->getValue($object, $prop);

if ($value === null && $this->settings->getSkipNull()) continue;

if ($value === null) {
$data[$jsonName] = null;
}
// a) special case: arrays
else if ($typeInfo->isArray) {
if (empty($value) && $this->settings->getSkipEmptyArrays()) continue;
$data[$jsonName] = $this->serializeArray($value);
}
// b) special case: DateTime
Expand Down
91 changes: 86 additions & 5 deletions src/JsonSettings.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,26 @@
namespace Pyther\Json;

use Pyther\Json\NamingPolicies\BaseNamingPolicy;
use Pyther\Json\Types\EnumFormat;

/**
* Json settings for serialization and deserialization.
*/
abstract class JsonSettings
class JsonSettings
{
// flags
private const INCLUDE_PROTECTED_FLAG = 1;

private int $flags = 0;
// on serialization only
private const USE_PRETTY_PRINT = 2;
private const DATETIME_AS_STRING = 4;
private const SKIP_NULL = 8;
private const SKIP_EMPTY_ARRAY = 16;

private int $flags = self::USE_PRETTY_PRINT | self::DATETIME_AS_STRING;
private ?BaseNamingPolicy $namingPolicy = null;
private string $dataTimeFormat = "Y-m-d\TH:i:s+";
private string $dataTimeFormat = \DateTime::W3C;
// on serialization only
private EnumFormat $enumFormat = EnumFormat::Value;

/**
* Set to true, to enable handling protected properties.
Expand Down Expand Up @@ -46,7 +54,7 @@ public function getNamingPolicy(): ?BaseNamingPolicy {


/**
* Set the default date time format.
* Set the default date time format (\DateTime::W3C by default).
* This can be overwriten per Property using "#[JsonDateTime(...)]"
*
* @param string $value
Expand All @@ -61,4 +69,77 @@ public function getDateTimeFormat(): string {
return $this->dataTimeFormat;
}

#region on serialization only

/**
* Enable or disable json indention (enabled by default).
* @param boolean $value
* @return static
*/
public function setPrettyPrint(bool $value = true): static {
$this->flags = $value ? $this->flags | self::USE_PRETTY_PRINT : $this->flags & ~self::USE_PRETTY_PRINT;
return $this;
}

public function getPrettyPrint(): bool {
return ($this->flags & self::USE_PRETTY_PRINT) != 0;
}

/**
* Enable or disable to serialize DateTime as string (enabled by default).
* @param boolean $value
* @return static
*/
public function setDateTimeAsString(bool $value = true): static {
$this->flags = $value ? $this->flags | self::DATETIME_AS_STRING : $this->flags & ~self::DATETIME_AS_STRING;
return $this;
}

public function getDateTimeAsString(): bool {
return ($this->flags & self::DATETIME_AS_STRING) != 0;
}

/**
* Defines the default serialization format for enumerations (EnumFormat::Value by default).
* @param EnumFormat $format
* @return static
*/
public function setEnumFormat(EnumFormat $format): static {
$this->enumFormat = $format;
return $this;
}

public function getEnumFormat(): EnumFormat {
return $this->enumFormat;
}

/**
* Define to skip null values.
* @param boolean $value
* @return static
*/
public function setSkipNull(bool $value = true): static {
$this->flags = $value ? $this->flags | self::SKIP_NULL : $this->flags & ~self::SKIP_NULL;
return $this;
}

public function getSkipNull(): bool {
return ($this->flags & self::SKIP_NULL) != 0;
}

/**
* Define to skip empty arrays.
* @param boolean $value
* @return static
*/
public function setSkipEmptyArray(bool $value = true): static {
$this->flags = $value ? $this->flags | self::SKIP_EMPTY_ARRAY : $this->flags & ~self::SKIP_EMPTY_ARRAY;
return $this;
}

public function getSkipEmptyArray(): bool {
return ($this->flags & self::SKIP_EMPTY_ARRAY) != 0;
}

#endregion
}

0 comments on commit e61434f

Please sign in to comment.