Skip to content

Commit

Permalink
[Objects] Create Experimental JsonSerializer (#32)
Browse files Browse the repository at this point in the history
Co-authored-by: onairmarc <[email protected]>
  • Loading branch information
onairmarc and onairmarc authored Dec 10, 2024
1 parent 2a5a563 commit 554f800
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
1 change: 1 addition & 0 deletions .git-blame-ignore-revs
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ f74b50a0c5a93e2042dd0899f67dc0d77d9f37b2
9e90f1089ce7ad5f2e9e3396c5764687690c96bb
68d26b0bcc009757d3a8c4b4aca534522832a35b
48e5c975f454025717dcbb55c82fa08e4f463241
11a1cd1aee3bca0336bfd1da90aec77f41577241
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
"php": "^8.2",
"illuminate/collections": "^10|^11",
"illuminate/support": "^10|^11",
"ramsey/uuid": "^4.7"
"ramsey/uuid": "^4.7",
"symfony/serializer": "^7.2"
},
"require-dev": {
"mockery/mockery": "^1.6",
Expand Down
44 changes: 44 additions & 0 deletions src/Objects/JsonSerializer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

namespace EncoreDigitalGroup\StdLib\Objects;

use Illuminate\Support\Collection;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

/** @experimental */
class JsonSerializer
{
protected static Collection $normalizers;
protected static Serializer $serializer;

public static function normalizers(): Collection
{
$defaultNormalizers = [
ObjectNormalizer::class,
];

if (!isset(static::$normalizers)) {
static::$normalizers = new Collection($defaultNormalizers);
}

return static::$normalizers;
}

public static function serialize(object $object): string
{
$serializer = new Serializer(static::normalizers()->all(), [(new JsonEncoder)]);
$normalized = $serializer->normalize($object);

return $serializer->serialize($normalized, "json");
}

public static function deserialize(string $class, string $data): mixed
{
$serializer = new Serializer(static::normalizers()->all(), [(new JsonEncoder)]);
$json = $serializer->deserialize($data, $class, "json");

return $serializer->denormalize($json, $class);
}
}

0 comments on commit 554f800

Please sign in to comment.